Preventing Object Copy in C++



In C++, when classes are created, we can copy it using some copy constructor or assignment operator. In this section we will see, how to prevent object copy of a class in C++. To prevent object copy, we can follow some rules. These are like below.

1. Creating private copy constructor and private assignment operator.

Example

#include <iostream>
using namespace std;
class MyClass {
   int x;
   public:
      MyClass() {
         //non-parameterized constructor
      }
      MyClass(int y): x(y) {
      }
   private:
      MyClass(const MyClass& obj) : x(obj.x) {
         //private copy constructor
      }
      MyClass& operator=(const MyClass& tmp_obj) {
         //private assignment operator (overloaded)
            x = tmp_obj.x;
         return *this;
      }
   };
 main() {
   MyClass ob(50);
   MyClass ob2(ob); // calls copy constructor
   ob2 = ob; // calls copy assignment operator
}

Output

[Error] 'MyClass::MyClass(const MyClass&)' is private
[Error] within this context
[Error] 'MyClass& MyClass::operator=(const MyClass&)' is private
[Error] within this context

2. Inherit dummy class with private copy constructor, and private assignment operator.

Example

#include <iostream>
using namespace std;
class DummyClass {
   public:
      DummyClass() {
      }
   private:
      DummyClass(const DummyClass& temp_obj) {
      }
      DummyClass& operator=(const DummyClass& temp_obj) {
      }
};
class MyClass : public DummyClass {
   int x;
   public:
      MyClass() { }
      MyClass(int y) : x(y) {
      }
};
int main() {
   MyClass ob1(50);
   MyClass ob2(ob1); // Calls copy constructor
   ob2 = ob1; // Calls copy assignment operator
}

Output

[Error] 'DummyClass::DummyClass(const DummyClass&)' is private
[Error] within this context
In function 'int main()':
[Note] synthesized method 'MyClass::MyClass(const MyClass&)' first
required here
In member function 'MyClass& MyClass::operator=(const MyClass&)':
[Error] 'DummyClass& DummyClass::operator=(const DummyClass&)' is
private
[Error] within this context
In function 'int main()':
[Note] synthesized method 'MyClass& MyClass::operator=(const
MyClass&)' first required here
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements