Sunday, April 14, 2013

Restricting the Copy constructor and assignment operator for a class object

Declare the copy constructor and copy assignment operator as private. By declaring a member function explicitly, you prevent compilers from generating their own version, and by making the functions private, you keep people from calling it.

Now the question comes, if we should declare them as protected or private. The advantage we get from declaring them private is that the error is generated at the compilation time and in case of the protected type access, it will be a linker time error.

So as Gopal says, earlier the better [:)]

Example follows:


class Base1 {

public:

        Base1():m_i(0) {}

private:
        Base1(const Base1&);
       Base1& operator=(const Base1&);

private:
        int m_i;
};

class Derived1 : public Base1 {

public:

Derived1():Base1(){}
Derived1(const Derived1& rhs):Base1(rhs) {}
Derived1& operator=(const Derived1& rhs){
   Base1::operator=(rhs);
}
};

int main ( void ) {

Base1 b1;
Derived1 d2;
Derived1 d1(d2);   // Compilation error here as base class copy constructor is private
return 0;
}

This will have compiler error.


If you declare the copy functions as protected, the linker error will be generated as follows:


/tmp/ccawBuy5.o: In function `Derived1::Derived1(Derived1 const&)':
test3.cpp:(.gnu.linkonce.t._ZN8Derived1C1ERKS_+0x14): undefined reference to `Base1::Base1(Base1 const&)'
collect2: ld returned 1 exit status







No comments:

Post a Comment