Broad Network


Constructors and Destructors in C++ Classes

Object Oriented Programming in C++ – Part 3

Forward: In this article I explain Constructors and Destructors in C++ Classes. I also explain the default assignment operator and copy constructor.

By: Chrysanthus Date Published: 23 Aug 2012

Introduction

This is part 3 of my series, Object Oriented Programming in C++. We saw a constructor function in part 1 of this series. That is an example of a constructor. The copy constructor is a name for another kind of constructor. You have the destructor (destructor function); this does the opposite of the constructor function. You have the assignment operator, which behaves similarly to the copy constructor. In this article I explain Constructors and Destructors in C++ Classes.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

Constructor Function
A constructor function is a function that is called automatically by C++ to initialize some of the properties of the instantiated object. You the programmer have the responsibility to define this function. If you do not want to initialize any of the properties of your class object or if your class does not have properties, then you do not need to define a constructor function; in that case C++ provides a default constructor function for you unknown to you. We saw this in the first part of the series. The constructor function is used to instantiate an object from a class. The following code illustrates the use of the default constructor function:

#include <iostream>
using namespace std;

class Calculator
    {
        public:
        int num1;
        int num2;

        int add ()
            {
                int sum = num1 + num2;
                return sum;
            }
    };


int main()
    {
        Calculator myObject;
        myObject.num1 = 2;
        myObject.num2 = 3;
        int result = myObject.add();
        cout << result;
        
        return 0;
    }

The default constructor function here is unknown to you. You use it indirectly. When instantiating an object (first line in main function) you give the name of the object without parentheses and of course without arguments. That name in that position calls the default constructor, unknown to you.

If you will initialize some of the properties of the class, then you need a constructor function; you have to define one. The constructor function must have the name of the class and must not have a returned value (not even void). The definition block of the constructor function should assign values to the properties. The initialization values are normally sent as arguments in the instantiation statement. The following code illustrates this:

#include <iostream>
using namespace std;

class Calculator
    {
        public:
        int num1;
        int num2;

        Calculator(int ident1, int ident2)
            {
                num1 = ident1;
                num2 = ident2;
            }

        int add ()
            {
                int sum = num1 + num2;
                return sum;
            }
    };


int main()
    {
        Calculator myObject(2,3);
        int result = myObject.add();
        cout << result;

        return 0;
    }

The two properties are initialized with the integer values, 2 and 3. Note the constructor function in the class description. It does not have a return type and its name is the name of the class. The first line in the main function instantiates an object. The name given to the object is myObject. The name of the object is given during instantiation at that position. At that position the name calls the constructor function. This object name is actually the constructor function call. Since the constructor function has parameters, this call needs corresponding arguments. So the name of the object takes arguments in parentheses. These arguments are for the parameters of the constructor function. In the definition of the constructor function, the values of the arguments are assigned to the properties of the object (see the constructor function definition in the class description).

Destructor Function
When a program no longer needs an instantiated object it destroys it. If you do not supply a destructor function, C++ supplies a default destructor for you, unknown to you. The program uses the destructor to destroy the object for you.

When should you define your own destructor function? In many cases you do not need a destructor function. However, if your class created dynamic objects, then you need to define your own destructor in which you will delete the dynamic objects. This is because dynamic objects are not normally deleted on their own. So, when the object is destroyed, the dynamic objects are deleted by the destructor function you define.

A destructor function has the same name as the class, and does not have a returned value. However you must precede the destructor with the tilde sign, which is ~ .

The following code illustrates the use of a destructor against dynamic objects:

#include <iostream>
using namespace std;

class Calculator
    {
        public:
        int *num1;
        int *num2;

        Calculator(int ident1, int ident2)
            {
                num1 = new int;
                num2 = new int;
                *num1 = ident1;
                *num2 = ident2;
            }

        ~Calculator()
            {
                delete num1;
                delete num2;
            }

        int add ()
            {
                int sum = *num1 + *num2;
                return sum;
            }
    };


int main()
    {
        Calculator myObject(2,3);
        int result = myObject.add();
        cout << result;

        return 0;
    }

The destructor function is automatically called, without you knowing, when the program no longer needs the object. If you defined a destructor function as in the above code, it will be executed. If you did not define a destructor function, C++ supplies you one, which the program uses unknown to you. However, this default destructor will not destroy dynamic objects.

Note: an object is destroyed as it goes out of scope.

Assignment Operator
With fundamental objects, you can copy the content of one object into the content of another object. You do this using the assignment (=) operator and the objects should be of the same type. The same thing happens with instantiated objects. Here, same type means the instantiated objects must be of the same class, that is, have the same class name. Consider the following code segment:

        Calculator myObject(2,3);
        Calculator hisObject(4,5);
        myObject = hisObject;

The first statement instantiates an object initializing it with the values, 2 and 3. The second statement instantiates a second object, initializing it with the values 4 and 5. There are two objects now with different attribute values. The third statement copies the content of the instantiated object, hisObject, to the content of the instantiated object myObject. The two objects now have the same content instead of the different contents they had before. The same content now, is that of hisObject. Read and try the following code:

#include <iostream>
using namespace std;

class Calculator
    {
        public:
        int num1;
        int num2;

        Calculator(int ident1, int ident2)
            {
                num1 = ident1;
                num2 = ident2;
            }

        int add ()
            {
                int sum = num1 + num2;
                return sum;
            }
    };


int main()
    {
        Calculator myObject(2,3);
        Calculator hisObject(4,5);
        myObject = hisObject;
        int result = myObject.add();
        cout << result;

        return 0;
    }

Note that when using the assignment operator, you do not need the parentheses for the object names.

The assignment operator to assign one instantiated object to another, mentioned above, is the default assignment operator provided by C++. You can come up with your own assignment operator, but I will not go into that.

The assignment operator copies the values of the attributes of one object (right operand) to become the values of the attributes of the other object (left operand). The default assignment operator works independently from the presence or absence of the constructor function (with or without parameters). In the above case, the output is 9 confirming that copy of the attribute values have been made from right operand object to left operand object.

In the assignment operation, the attributes without values and the method definitions are also copied.

Copy Constructor
A copy constructor function operates similarly to the assignment operator. It effectively copies the values of the attributes of one object to become the values of the attributes of the other object. Here we do not talk about right and left operands. The copy constructor is produced through parentheses to the other object name, whose attribute values are to change. This is done when the other object is being instantiated. Consider the following code segment:

        Calculator hisObject(4,5);
        Calculator myObject(hisObject);

The first statement instantiates an object with the name, hisObject. The second statement instantiates a second object (myObject) and in the instantiation process, the values of the attributes of the first object are copied as values of the attributes to the second object. Also, all members are copied.

What I have described here, is the default copy constructor, provided by C++, unknown to you. You can define your own copy constructor, but I will not go into that. Read and try the following code:

#include <iostream>
using namespace std;

class Calculator
    {
        public:
        int num1;
        int num2;

        Calculator(int ident1, int ident2)
            {
                num1 = ident1;
                num2 = ident2;
            }

        int add ()
            {
                int sum = num1 + num2;
                return sum;
            }
    };


int main()
    {
        Calculator hisObject(4,5);
        Calculator myObject(hisObject);
        int result = myObject.add();
        cout << result;

        return 0;
    }

Note: for the assignment and copy function, the object being copied is called the source object, while the object receiving the copy is called the target object.

Conclusion
You have the function constructor; the function destructor, the assignment operator and the copy function constructor. If you do not define any of these for your class, C++ provides corresponding default features for you. Many programs define assignment operator, copy constructor function and destructor function only if they have dynamic objects in their classes.

Let us end here and continue in the next part of the series.

Chrys

Related Courses

C++ Course
Relational Database and Sybase
Windows User Interface
Computer Programmer – A Jack of all Trade – Poem
NEXT

Comments

Become the Writer's Fan
Send the Writer a Message