8.5 Copy constructors PDF

Title 8.5 Copy constructors
Course Intermediate Programming Methodologies in C++
Institution De Anza College
Pages 4
File Size 112.8 KB
File Type PDF
Total Downloads 104
Total Views 150

Summary

Object copying without a copy constructor
The animation below depicts a common issue that occurs when an object is transferred by value to a function and the object has no copy constructor.
The solution is to create a copy constructor, which is called automatically when a class type obje...


Description

8.5 Copy Constructor Copy constructor Solution to the problem above is to create copy constructor, that is automatically called when: object of the class type is passed by value to a fuction and when an object is initialized by copying another object during declaration Example: MyClass classObj2 = classObj1; //or obj2Ptr = new MyClass(classObj1);

The copy constructor makes a new copy of all data members (including pointers) — a deep copy.

If we don't define copy constructor, then compiler implicitly defines a constructor with statements that perform memberwise copy , which simply copies using assignment newObj.member1 = origObj.member1, newObj.member2 = origObj.member2, etc

This creates a shallow copy of the object. It's fine for many classes, but we need deep copy for objects that have data members pointing to dynam allocated mmry.

How is it called? With a single pass-by-reference argument class MyClass { public: MyClass(const MyClass& origObject); }

Copying object w/ copy constructor. Program works fine!

#include using namespace std; class MyClass { public: MyClass(); MyClass(const MyClass& origObject); //copy constructor ~MyClass(); //Set member value dataObject void SetDataObject(const int setVal) { *dataObject = setVal; } //Return member value dataObject int GetDataObject() const { return *dataObject; } private: int* dataObject; //data member }; //Default constructor MyClass::MyClass() { cout...


Similar Free PDFs