C++ Copy Constructor
The C++ copy constructor is very important when working with objects. It allows for objects to be passed by value to function arguments and then returned from functions. If a class dynamically allocates memory then it must have a custom copy constructor written.
#include <iostream>
using namespace std;
class Copy
{
private:
int copyCount;
public:
Copy() : copyCount(0) {}
Copy(const Copy &obj) : copyCount(obj.copyCount + 1) // custom copy constructor
{
cout << "copy operation; copy number " << copyCount << endl;
}
};
Copy MakeCopies(Copy byValue) // invoke copy constructor
{
return byValue; // invoke copy constructor
}
int main()
{
Copy copy;
MakeCopies(copy);
return 0;
}

Make a copy constructor private to prevent the object from being copied.
#include <iostream>
using namespace std;
class Copy
{
private:
int copyCount;
Copy(const Copy &obj) {} // custom copy constructor
public:
Copy() : copyCount(0) {}
};
Copy MakeCopies(Copy byValue) // invoke copy constructor
{
return byValue; // invoke copy constructor
}
int main()
{
Copy copy;
MakeCopies(copy);
return 0;
}
Reader Postings:
log in to post comments