Rule of 3 in C++

In cpp, the law of Big three states that

If any of the special functions is declared in the class, the other two must be implemented.

The special functions in a class are

  • Destructor
  • Copy constructor
  • Assignment operator

Although, these functions are implicitly provided by the compiler. But when the class implements composition or inheritance, the set of 3 functions should be implemented.

Let us consider the below example:

class Sample
{
    //all default
};

int main()
{
    Sample objSample;
    return 0;
}

The class does not have any object or no operations to be done. So set of default special member functions are much enough to clean up the object.
Let us now modify the above code.

class Sample
{
    ~Sample() {}
    Sample(Sample& objSample);
};
int main()
{
    Sample objSample;
    Sample objCopy(objSample);

    return 0;
}

When the main(..) is executed, the destructor of the Sample class will be called twice as two objects are defined. The default copy constructor will just do the reference/shared copy and not the deep copy of the object. Hence when the second object is deleted, the program will crash.

int main()
{
    Sample objSample;
    Sample objAssign;
    objAssign = objSample;

    return 0;
}

Let us consider the above code, the default assignment operator will assign the reference assignment and not copy the data of the object to the other one. This will also crash when the destructor for the second object is executed.

Hence when the class destructor needs to be defined for the object, we should always define all the other special member function.

About these ads
Tagged with: , , , , , , ,
Posted in CPP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 353 other followers

%d bloggers like this: