Class in C++

A constructor in C++ is a special ‘MEMBER FUNCTION’ having the same name as that of its class which is used to initialize some valid values to the data members of an object. It is executed automatically whenever an object of a class is created. The only restriction that applies to the constructor is that it must not have a return type or void. It is because the constructor is automatically called by the compiler and it is normally used to INITIALIZE VALUES. The compiler distinguishes the constructor from other member functions of a class by its name which is the same as that of its class. ctorz is an abbreviation of constructor in C++. 

The constructor can be defined as a  class in the same way as that of normal member functions and can access any of its data members. The syntax for defining constructor inside the class body is as follows:

EXAMPLE:

class CLASSNAME
{
   ………
  public :
               CLASSNAME([parameter_list])  // constructor definition
             {
                . . . . . . 
             }
              . . . . . . . .
};

You can also define a constructor with its declaration inside the class body and seeing what follows.

class CLASSNAME
 {
 . . . . . . . . 
public:
          CLASSNAME ([parameter_list]);//Constructor declaration
         . . . . . . . . .
};  
CLASSNAME: :CLASSNAME([parameter_list])//Constructor Definition
{
. . . . . . . . . . .
}

  • The above syntax shows the declaration and definition of a constructor. It is defined outside the class in the same way as we define a member function outside the class using the scope resolution operator.
  • One should note that the name of the constructor is the same as that of its class. The constructor parameter list enclosed in the square brackets is optional and may contain zero or more parameters.
  • We should declare the constructor in the public section of the class as they are invoked automatically when the objects are created.

DEFAULT CONSTRUCTOR

  • A constructor to which no arguments are passed is called the Default constructor. It is also called a constructor with no parameters.
  • Using the default constructor, data members can be initialized to some realistic values in its definition even though no arguments are specified explicitly. Each time an object is created, a constructor is invoked. If we define objects and classes without defining any constructor for a class. So in such a situation, the compiler automatically generates a constructor of its own without any parameters i.e. Default Constructor.
  • This compiler generates a default constructor which is invoked automatically whenever any object of the class is created but doesn’t perform any initialization. However, if you define a default constructor explicitly, the compiler no longer generates a default constructor for you.

The following are the key points while defining constructors for a class:

  • A constructor has the same name as that of the class to which it belongs to.
  • If you don’t openly provide a constructor of your own then the compiler generates a default constructor for you.
  • A constructor can preferably be used for initialization and not for input/output operations.
  • Constructors may not be static.
  • Constructors are also used to locate memory at run time using the new operator.
  • Constructors cannot be virtual.
  • A constructor is executed repeatedly whenever the objects of a class are created.
  • We can declare more than one constructors in a class i.e. constructors can be overloaded.

PARAMETERIZED CONSTRUCTOR

  • Unlike default constructors which do not take any parameters, it is however possible to pass one or more arguments to a constructor. 
  • Constructors that can take arguments are known as parameterized constructors. 

The syntax for declaring parameterized constructor inside the set:

class class_name 
{

public:
  class_name(variables) //Parameterized constructor declared.
  {
  
  }
};

The syntax for declaring parameterized construct outside the class:

class class_name
{
   
};
class_name :: class_name() //Parameterized constructor declared.
{
      
}
 

CONSTRUCTOR OVERLOADING

  • In some programs, a class had only one constructor which either zero, one, or more parameters. The constructor is key for object initialization. The mechanism of the constructor is made considerably more powerful by uniting with the feature of overloading. It is made possible by providing more than one constructor in a class called Constructor overloading.

 C++ Constructor Overloading Example

/*.....A program to feature the concept of constructor overloading.......... */
#include <iostream>
using namespace std;
class ABC
{
     private:
        int x,y;
     public:
        ABC ()       //constructor 1 with no arguments
       {
            x = y = 0;
        }
        ABC(int a)    //constructor 2 with one argument
       {
             x = y = a;
        }
        ABC(int a,int b)    //constructor 3 with two argument
        {
              x = a; 
              y = b;
        }
        void display()
        {
              cout << "x = " << x << " and " << "y = " << y << endl;
        }
};

int main()
{
     ABC cc1; //constructor 1
     ABC cc2(10); //constructor 2
     ABC cc3(10,20); //constructor 3
     cc1.display();
     cc2.display();
     cc3.display();
     return 0;
 }  //end of program

OUTPUT:

X = 10 and y = 0
X = 10 and y = 10
x = 10 and y = 2

CONSTRUCTOR IN ARRAY OF OBJECTS

Constructors are called for every object of a class being created. Whenever an array of class objects is defined then a default constructor is called for each object of the array.

In other words, each object of the array is initialized with the same set of values using the default argument constructor. 

For example:

rectangle r[20];

It defines an array of 20 objects of the class rectangle. Each object (element) of the array rectangle invokes the default constructor for initializing its data members. We can also initialize the value to individual objects of an array explicitly using the parameterized constructor which is shown below:

rectangle  r[3]={rectangle(5,6),rectangle(7,8),rectangle(5,7)};

Three objects r[0], r[1], r[2] are created and initialized using the constructor with two parameters as only two arguments are passed. Here, the constructor with a two-parameter is called explicit for initializing individual objects of the array.

Initialize Array of objects with parameterized constructors in C++

When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to build objects to use the data and access functions specified in the class.

Syntax:

1

2

3  

Specific methods for initializing the Parameterized Constructors list of objects:

Using malloc(): Use the malloc() method to avoid calling a non-parameterized constructor. The “Malloc” or “Memory Allocation” method in C++ is used to dynamically allocate the specified size of a single large block of memory. It returns a sort of void pointer that can be thrown into a pointer of any kind.

#include <iostream>
#define P 5
using namespace std;
class Test
{
    // private variables
    int a, b;
public:
    // parameterized constructor
    Test(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
    // function to print
    void print()
    {
        cout << a << " " << b << endl;
    }
};
int main()
{
    // allocating dynamic array
    // of Size N using malloc()
    Test* arr = (Test*)malloc(sizeof(Test) * P);
    // calling constructor
    // for each index of array
    for (int k = 0; k < P; k++)
          {
        arr[k] = Test(k, k + 1);
    }
    // printing contents of array
    for (int k = 0; k < P; k++)
           {
        arr[k].print();
    }
    return 0;
}

Output:

0 1  1 2  2 3  3 4  4 5  

Work Double pointer

  • The pointer to a pointer is a set of complex indirect or a pointer chain. A pointer often holds the address of a variable. When we narrate a pointer to a pointer, the first pointer contains the second pointer‘s address, which points to the location containing the real value, as shown below.
  • Now we can allocate a number of blocks to be assigned, so we have to call the parameterized constructor to initialize for each index using the new keyword. 
#include <iostream>
#define T 10
using namespace std;
class Test {
          // private variables
          int s, t;
public:
          // parameterized constructor
          Test(int s, int t)
                   : s(s), t(t)
          {
          }
          // function to print
          void print()
          {
                   cout << s << " " << t << endl;
          }
};
int main()
{
          // allocating array using
          // pointer to pointer concept
          Test** arr = new Test*[T];
          // calling constructor for each index
          // of array using new keyword
          for (int i = 0; i < T; i++) {
                   arr[i] = new Test(i, i + 1);
          }
          // printing contents of array
          for (int i = 0; i < T; i++) {
                   arr[i]->print();
          }
          return 0;
}

Output:

0 1  1 2  2 3  3 4  4 5  5 6  6 7  7 8  8 9  9 10

Using a new keyword

  • On the Heap, the new operator denotes a memory allocation request. If there is enough memory, the new operator identifies the memory and returns the newly allocated and configured memory address to the variable name. 
  • Here, point-variable is the information-type pointer. Data type could be any type of built-in data along with an array or any type of user-defined data such as structure and class.
  • If we add a parameterized constructor, a new keyword requires a non-parameterized constructor for dynamic initialization. So we’re going to use a dummy constructor for that.  
#include <iostream>
#define E 15
using namespace std;
class Test {
    // private variables
    int m, n;
public:
    // dummy constructor
    Test() {}
    // parameterized constructor
    Test(int m, int n)
    {
        this->m = m;
        this->n = n;
    }
    // function to print
    void print()
    {
        cout << m << " " << n << endl;
    }
};
int main()
{
    // allocating dynamic array
    // of Size N using new keyword
    Test* arr = new Test[E];
    // calling constructor
    // for each index of array
    for (int j = 0; j < E; j++) {
        arr[j] = Test(j, j + 1);
    }
    // printing contents of array
    for (int j = 0; j < E; j++) {
        arr[j].print();
    }
    return 0;
}

OUTPUT :

0 1  1 2  2 3  3 4  4 5  5 6  6 7  7 8  8 9  9 10  11 12  

CONSTRUCTOR WITH DEFAULT ARGUMENTS

  • By defining constructors with default arguments, this facility allows a constructor called to specify the fewer number arguments instead of passing all the arguments defined in the constructor. If the constructor called during object creation, doesn’t specify all the arguments then the omitted arguments can take default values specified in the constructor definition. 
  • However, if the constructor is declared inside and defined outside the class then default values are provided in the constructor declaration and not in its definition. 
  • When the constructor call specifies the arguments corresponding to the default arguments then the past arguments always override the default values.
  • Constructors with default arguments may help to reduce the size of the class as there is no need to make multiple constructors in the class. This can be seen by comparing the above program with the previous program of the complex number. 
  • However, in certain situations, if it is likely that the default arguments value will change then it is better to use an overloaded constructor instead of a single constructor with default arguments.

INITIALIZER LIST

  • C++provides an alternative syntax for initializing data members of the objects in the constructor known as Initialize list. A rectangle constructor with two parameters can be rewritten to use the initializer list is as follows: rectangle(int a, int b): length(a), breath(b) {. . . }
  • The initialize list is placed between the parameters list and the opening brace of the body of the constructor. The list begins with the colon(:)and is separated by commas.
    Each initialize clause simply names the data members and in the parentheses list the value to be used to initialize the data member.
  • When the constructor is declared inside and defined outside the class using scope resolution operator then the member initialization list can only be specified within the constructor definition and not in its declaration. An initialize list allows initialization of data members at the time of their creation which is more efficient as values are assigned before the constructor even starts to execute.

Dynamic Initialization using Constructor

  • Data members of an object after creation can be initialized at run time using constructors. Such initialization of data members is called dynamic initialization.
  • The main advantage of dynamic initialization is the ability to allow different modes of initialization using overloaded constructions. Hence, the user can provide the different formats of data depending on the requirement.
  • Consider an example of displaying the height of a person in feet and inches.
    The different formats for specifying the height of a person can be 5 feet, 5.5 feet, and explicitly specifying like 5 feet and 8 inches.
#include<iostream.h>
#include<conio.h>
Class height
{
   Private:
     Int feet:
    Double inches;
  Public:
    Height(int f)
   {
      Feet=f;
      Inches=0.0;
  }
  Height(double f)
  {
     Feet=int(f);
     Inches=(f-int(f))*12.0;
  }
  Height()
  {
       Feet=inches=0;
  }
  Height(int f, double in)
  {
    Feet=f; inches=in;
  }
  Void show()
  {
      Cout<<”feet=”<<feet<<” inches=”<<inches<<endl;
  }
}://end of class specification
Int main()
{   
    Clrscr();
    Height h1, h2, h3;//  default constructor invoked
    Int ht_feet;
   Cout<<”Enter height in term of feet only :”;
   Cin<<ht_feet;
   H1 = height(ht_feet);
   Double ht_ fract;
   Cout<<”Enter height in terms of feet in fractional forms : “;
  Cin>>ht_fract;
  H2= height(ht_fract);
  Int ft1;
   Double in1;
   Cout<<”Enter height in terms of feet and inches : “ ;
   Cin>>ft1>>in1;
  H3 = height(ft1, in1;
  H1.show();  h2.show();   h3.show();
    Getch();  return 0;
}

OUTPUT:

Enter height in terms of feet only: 5

Enter height in terms of feet in the fractional form: 5.5

Enter height in terms of feet and inches: 5 8 

Feet = 5  Inches = 0

Feet = 5 Inches = 6

Feet = 5 Inches = 8

Explanation:

In this program, we have four constructors. The arguments to the parameterized constructors are provided at run time. The  user can specify the height of a person in any of the following formats:

  • Not specifying any height and hence default constructor is invoked which initialize feet and inches to 0 each.
  • Specifying height only in terms of feet in integral form and for this constructor height(int); is invoked.
  • Specifying height only in terms of feet in fractional form and for this, constructor height(double); is invoked.
  • Specifying height in inches, constructor height(int, double); is invoked.

The constructor height ()is overloaded and which one will be called depends on the arguments specified by the constructor.

This brings us to the end of the blog on Constructor in C++. We hope that you were able to gain some knowledge from the same. If you wish to learn more such concepts about constructor in C++ or any other programming languages, you can join Great Learning Academy’s Free Online Courses today.

Also, if you are preparing for Interviews, check out these Interview Questions for C++ to ace it like a pro.

0

LEAVE A REPLY

Please enter your comment!
Please enter your name here

four × three =