Skip to main content
Engineering LibreTexts

13.2.3: Classes and Objects - Constructor and Destructor

  • Page ID
    29115
  • Constructors

    Constructors are special class members which are called by the compiler every time an object of that class is instantiated. Constructors have the same name as the class and may be defined inside or outside the class definition. Constructors are usually used to setup the object that is being created. If you do NOT actually code and call a constructor then C++ will simply create an object.

    There are 3 types of constructors:

    • Default constructors
    • Parametized constructors
    • Copy constructors
    // C++ program to demonstrate constructors
    
    
    #include <bits/stdc++.h>
    using namespace std;
    class Courses
    {
        public:
        int id;
        
        //Default Constructor
        Courses()
        {
            cout << "Default Constructor called" << endl;
            id=-1;
        }
        
        //Parametized Constructor
        Courses(int x)
        {
            cout << "Parametized Constructor called" << endl;
            id=x;
        }
    };
    int main() {
        
        // obj1 will call Default Constructor
        Courses courseObj1;
        cout << "Courses id is: " << courseObj1.id << endl;
        
        // obj1 will call Parametized Constructor
        Courses courseObj2(21);
        cout << "Courses id is: " << courseObj2.id << endl;
        return 0;
    }
    
    

    In this code we show both the default constructor, which has no arguments, and the parameterized constructor which takes arguments. Notice that the constructor method is simply the same as the name of the class we are constructing. Also, it is valid to have a default constructor with arguments. 

    The constructor gets called when the instance of a class is created. In our code above, we have the statement: Courses courseObj1; - at this point in our code the constructor method is called and memory is allocated for our object. This is shown in our output where the statement from within the constructor is output PRIOR to the statement in the code. 

    Default Constructor called
    Geek id is: -1
    Parametrized Constructor called
    Geek id is: 21
    

    Copy Constructor  is a member function which initializes an object using another object of the same class. A copy constructor has the following general function prototype:

        ClassName (const ClassName &old_obj); 

    Here is an example of the copy constructor.

    #include<iostream>
    using namespace std;
    
    class Point
    {
      private:
        int x, y;
    
      public:
        Point(int x1, int y1)
        {
            x = x1;
            y = y1;
        }
    
        // Copy constructor takes the input value
        Point(const Point &inputPt)
        {
            x = inputPt.x;
            y = inputPt.y;
        }
    
        int getX()
        {
            return x;
        }
        int getY()
        {
            return y;
        }
    };
    
    int main()
    {
        Point myP1(10, 15); // Normal constructor is called here
        Point myP2 = myP1;  // Copy constructor is called here
    
        // Let us access values assigned by constructors
        cout << "myP1.x = " << myP1.getX() << ", myP1.y = " << myP1.getY() << endl;
        cout << "myP2.x = " << myP2.getX() << ", myP2.y = " << myP2.getY() << endl;
    
        return 0;
    }
    

    The place we need to pay attention in the above code is where we declare myPt2 - this is where the copy constructor gets called. Our copy constructor simply copies the object variable values from the myPt1 object to the variables in the new myPt2 object. You can see from the output that both of these objects have the same variable values because of this copy. It is allowed to write copy constructors that do whatever you need them to do. The copy constructor is not restricted to simply 

     

    myP1.x = 10, myP1.y = 15
    myP2.x = 10, myP2.y = 15

     

    Destructors

    Destructor is another special member function that is called by the compiler when the scope of the object ends.

    // C++ program to explain destructors
    
    
    #include <iostream>
    using namespace std;
    class Courses
    {
        public:
        int id;
        
        //Definition for Destructor
        ~Courses()
        {
            cout << "Destructor called for id: " << id <<endl;
        }
    };
    
    
    int main()
    {
        Courses newObj1;
        newObj1.id=7;
        int i = 0;
        while ( i < 5 )
        {
            Courses newObj2;
            newObj2.id=i;
            i++;         
        } // Scope for obj2 ends here
    
    
        return 0;
    } // Scope for obj1 ends here
    
    

    Just as we have a constructor, we have destructors that destroy the objects and release the memory back to the system. 

    One note in the code above is to look at newObj2. It is created within the block of code that is associated with the while loop. As we said when we discussed variable scope - a variable is only available within its block of code, or sub-blocks. So, newObj2 is created within this block, BUT, when we hit the bottom this loop newobj2 goes "out of scope" and the destructor method is called. Each time through the loop newObj2 is created again, and assigned an increasing id (we are incrementing i++). Then finally when the program ends newObj1 is destroyed as well, as you can see in the output below.

    Destructor called for id: 0
    Destructor called for id: 1
    Destructor called for id: 2
    Destructor called for id: 3
    Destructor called for id: 4
    Destructor called for id: 7

     Adapted from:
    "C++ Classes and Objects" by BabisSarantoglouGeeks for Geeks is licensed under CC BY-SA 4.0