C++ Constructors

A constructor is a special type of member function that initialises an object automatically when it is created.

Compiler identifies a given member function is a constructor by its name and the return type.

Constructor has the same name as that of the class and it does not have any return type. Also, the constructor is always public.

How constructor works? :


Simple lets take an example :

                class temporary
                {
                private: 
                    int x;
                    float y;
                public:
                    // Constructor
                    temporary(): x(1), y(2)
                    {
                        // Body of constructor
                    }
                    ... ..  ...
                };

                int main()
                {
                    Temporary t1;
                    ... .. ...
                }
                



In above code temporary() is a constructor.

When an object of class temporary is created, the constructor is called automatically, and x is initialized to 1 and y is initialized to 2.

So this is the main purpose of constructor to initialize variable at the time of construction created .

Lets take an real life example of constructor :


Every single person in this world has a unique name. Persons name helps us to identify them. So, name is the class name for every person. for example my name is Abhijeet so Abhijeet is the name of my class.

Class Abhijeet{

}


Now, we can say my behaviour and nature is mentioned in this class and this class represents me.

Now there is a situation when one person says my name, when he says “Abhijeet” I tried to figure out who is that person, I turned toward him and then asks him for what reason he is calling me.

When that person says “Abhijeet”, he knowingly/unknowingly called default constructor Abhijeet. This default constructor defines my response that I did (as mentioned above).

Use of Constructor in C++ :

Suppose you are working on 100’s of Person objects and the default value of a data member age is 0. Initialising all objects manually will be a very tedious task.

Instead, you can define a constructor that initialises age to 0. Then, all you have to do is create a Person object and the constructor will automatically initialise the age.

These situations arise frequently while handling array of objects.

Also, if you want to execute some code immediately after an object is created, you can place the code inside the body of the constructor.

Lets take an real life example

Consider Building is your class . Government by default gives few rules and regulations to be followed while constructing a building ,Default rules are your default constructors which are generated by compilers.

Now the question is like what about the inner view of your building and other related features of building like total no.of rooms that can be created and so on are the features that a builder decides based on his Page on budget.so now adding up the no.of rooms for a particular type of building is some x and giving a detail of every feature is a User defined constructor which we need to write. You can access elements of an array by using indices.

Lets Take an coding example :

 

                    #include <iostream>
                    using namespace std;
                    class Area
                    {
                    private:
                    int length;
                    int breadth;
                    public:
                    // Constructor
                    Area(): length(5), breadth(2){ }
                    void GetLength()
                    {
                    cout << "Enter length and breadth respectively: ";
                    cin >> length >> breadth;
                    }
                    int AreaCalculation() {  return (length * breadth);  }
                    void DisplayArea(int temp)
                    {
                    cout << "Area: " << temp;
                    }
                    };
                    int main()
                    {
                    Area A1, A2;
                    int temp;
                    A1.GetLength();
                    temp = A1.AreaCalculation();
                    A1.DisplayArea(temp);
                    cout << endl << "Default Area when value is not taken from user" << endl;
                    temp = A2.AreaCalculation();
                    A2.DisplayArea(temp);
                    return 0;
                    }
                



Explaination of the code :

class Area is created to handle area related functionalities. It has two data members length and breadth.

A constructor is defined which initialises length to 5 and breadth to 2.

We also have three additional member functions GetLength(), AreaCalculation() and DisplayArea() to get length from the user, calculate the area and display the area respectively.

When, objects A1 and A2 are created, the length and breadth of both objects are initialized to 5 and 2 respectively, because of the constructor.

Then, the member function GetLength() is invoked which takes the value of length and breadth from the user for object A1. This changes the length and breadth of the object A1.

Then, the area for the object A1 is calculated and stored in variable temp by calling AreaCalculation() function and finally, it is displayed.

For object A2, no data is asked from the user. So, the length and breadth remains 5 and 2 respectively.

Then, the area for A2 is calculated and displayed which is 10.

Output :
                        Enter length and breadth respectively: 6
                        7
                        Area: 42
                        Default Area when value is not taken from user
                        Area: 10
                        
                



Types of Constructors in C++ :

Constructors are of three types:
1. Default Constructor
2. Parametrized Constructor
3. Copy COnstructor

1. Default Constructor :

Default constructor is the constructor which doesn’t take any argument. It has no parameter.

                        class Cube
                        {
                            public:
                            int side;
                            Cube()
                            {
                                side = 10;
                            }
                        };
                        
                        int main()
                        {
                            Cube c;
                            cout << c.side;
                        }

                


In this case, as soon as the object is created the constructor is called which initializes its data members.

A default constructor is so important for initialization of object members, that even if we do not define a constructor explicitly, the compiler will provide a default constructor implicitly.(Note this point defaulr constructor compiler will provide by default)

2. Parameterized Constructors :

These are the constructors with parameter. Using this Constructor you can provide different values to data members of different objects, by passing the appropriate values as argument.

                        class Cube
                        {
                            public:
                            int side;
                            Cube(int x)
                            {
                                side=x;
                            }
                        };
                        
                        int main()
                        {
                            Cube c1(1);
                            Cube c2(2);
                            Cube c3(3);
                            cout << c1.side;
                            cout << c2.side;
                            cout << c3.side;
                        }
                



we have initialized 3 objects with user defined values. We can have any number of parameters in a constructor.

Output :

                    1 
2
3

Constructor Overloading in C++ :

Just like other member functions, constructors can also be overloaded. Infact when you have both default and parameterized constructors defined in your class you are having Overloaded Constructors, one with no parameter and other with parameter.

Lets take an example :
                        class Student
                        {
                            public:
                            int rollno;
                            string name;
                            // first constructor
                            Student(int x)
                            {
                                rollno = x;
                                name = "None";
                            }
                            // second constructor
                            Student(int x, string str)
                            {
                                rollno = x;
                                name = str;
                            }
                        };
                        
                        int main()
                        {
                            // student A initialized with roll no 10 and name None
                            Student A(10);
                            
                            // student B initialized with roll no 11 and name John
                            Student B(11, "John");
                        }
                

 

Important Notes :

In above case we have defined two constructors with different parameters, hence overloading the constructors.

One more important thing, if you define any constructor explicitly, then the compiler will not provide default constructor and you will have to define it yourself.

In the above case if we write Student S; in main(), it will lead to a compile time error, because we haven’t defined default constructor, and compiler will not provide its default constructor because we have defined other parameterized constructors.

Destructor In C++ :

Destructor is a special class function which destroys the object as soon as the scope of object ends. The destructor is called automatically by the compiler when the object goes out of scope.

The syntax for destructor is same as that for the constructor, the class name is used for the name of destructor, with a tilde ~ sign as prefix to it.

Example to see how Constructor and Destructor are called
                        class A
                        {
                            // constructor
                            A()
                            {
                                cout << "Constructor called";
                            }
                        
                            // destructor
                            ~A()
                            {
                                cout << "Destructor called";
                            }
                        };
                        
                        int main()
                        {
                            A obj1;   // Constructor Called
                            int x = 1
                            if(x)
                            {
                                A obj2;  // Constructor Called
                            }   // Destructor Called for obj2
                        } //  Destructor called for obj1
                

 

Output :

 

                        Constructor called
                        Constructor called
                        Destructor called
                        Destructor called
                



When an object is created the constructor of that class is called. The object reference is destroyed when its scope ends, which is generally after the closing curly bracket } for the code block in which it is created.

The object obj2 is destroyed when the if block ends because it was created inside the if block. And the object obj1 is destroyed when the main() function ends.

Important Properties of Destructor

The following properties of destructor:
1. A destructor invoked implicitly by the compiler upon exit from the program.
2. It is used to clean up the storage that is no longer accessible.
3. It never takes any argument nor return any value.


It is a good practice to declare destructor in a program since it releases memory space for future use. Objects are destroyed in the reverse order of creation.

 

Lets do some exercises :

 

1. Write a C++ program to read seven numbers and sorts them in descending order :

 

                    Enter 7 numbers :
                    2
                    4
                    6
                    1
                    7
                    9
                    8
                    Output :
                    9
                    8
                    7
                    6
                    4
                    2
                    1
                
2. Write a C++ program to which replace all the words “dog” with “cat” .

 

                    Input :

                         The quick brown fox jumps over the lazy dog.
                         You can assume that the number of characters 
                         in a text is less than or equal to 1000.
                    Output :
                        The quick brown fox jumps over the lazy cat.
                         You can assume that the number of characters 
                         in a text is less than or equal to 1000.

                

C++ friend Function and friend Classes

If a function is defined as a friend function then, the private and protected data of a class can be accessed using the function.

For accessing the data, the declaration of a friend function should be made inside the body of the class (can be anywhere inside class either in private or public section) starting with keyword friend.

Declaration of friend function in C++ :

 

                    class class_name    
                    {    
                        friend data_type function_name(argument/s); 
                                   // syntax of friend function.  
                    };   
                


In the above declaration, the friend function is preceded by the keyword friend. The function can be defined anywhere in the program like a normal C++ function. The function definition does not use either the keyword friend or scope resolution operator.

Important Properties of friend functions in C++ :


The function is not in the scope of the class to which it has been declared as a friend.
It cannot be called using the object as it is not in the scope of that class.
It can be invoked like a normal function without using the object.
It cannot access the member names directly and has to use an object name and dot membership operator with the member name.
It can be declared either in the private or the public part.
.

Lets take an Coding Example :
                    /* C++ program to demonstrate the working of friend function.*/
                    #include < iostream>
                    using namespace std;
                    class Distance
                    {
                        private:
                            int meter;
                        public:
                            Distance(): meter(0) { }
                            //friend function
                            friend int addSix(Distance);
                    };
                    // friend function definition
                    int addSix(Distance d)
                    {
                        //accessing private data from non-member function
                        d.meter += 6;
                        return d.meter;
                    }
                    int main()
                    {
                        Distance D;
                        cout<<"Distance Is :  "<< addSix(D);
                        return 0;
                    }
                    
                

 

Output :
                    Distance is : 6
                



Here, friend function addSix() is declared inside Distance class. So, the private data meter can be accessed from this function.

Though this example gives you an idea about the concept of a friend function, it doesn’t show any meaningful use.

A more meaningful use would to when you need to operate on objects of two different classes. That’s when the friend function can be very helpful.

You can definitely operate on two objects of different classes without using the friend function but the program will be long, complex and hard to understand.

friend Class in C++ Programming :

Similarly, like a friend function, a class can also be made a friend of another class using keyword friend. For example:

When a class is made a friend class, all the member functions of that class becomes friend functions.

In this program, all member functions of class B will be friend functions of class A. Thus, any member function of class B can access the private and protected data of class A. But, member functions of class A cannot access the data of class B.

Lets take an Example :
                    // friend class
                    #include <iostream>
                    using namespace std;
                    
                    class Square;
                    
                    class Rectangle {
                        int width, height;
                      public:
                        int area ()
                          {return (width * height);}
                        void convert (Square a);
                    };
                    
                    class Square {
                      friend class Rectangle;
                      private:
                        int side;
                      public:
                        Square (int a) : side(a) {}
                    };
                    
                    void Rectangle::convert (Square a) {
                      width = a.side;
                      height = a.side;
                    }
                      
                    int main () {
                      Rectangle rect;
                      Square sqr (4);
                      rect.convert(sqr);
                      cout << rect.area();
                      return 0;
                    }

                



Code Explaination :

In this example, class Rectangle is a friend of class Square allowing Rectangle’s member functions to access private and protected members of Square. More concretely, Rectangle accesses the member variable Square::side, which describes the side of the square.

There is something else new in this example: at the beginning of the program, there is an empty declaration of class Square. This is necessary because class Rectangle uses Square (as a parameter in member convert), and Square uses Rectangle (declaring it a friend).

Friendships are never corresponded unless specified: In our example, Rectangle is considered a friend class by Square, but Square is not considered a friend by Rectangle. Therefore, the member functions of Rectangle can access the protected and private members of Square but not the other way around. Of course, Square could also be declared friend of Rectangle, if needed, granting such an access.

Another property of friendships is that they are not transitive: The friend of a friend is not considered a friend unless explicitly specified.