Tutorial Study Image

C++ Constructors


January 3, 2023, Learn eTutorial
658

As we all know  C++  is an object-oriented programming language, So we may use classes and objects to reduce complexity as well as it also improves code reusability in our program. Two essential class characteristics that help us to achieve this purpose are constructor and destructor.

With the help of simple examples, we will learn about the C++ constructor as well as its type in this tutorial.

What do you mean by constructors in C++?

A constructor is a  very special member function that shares the same name as that of the class, which has no return type and is called automatically whenever a new instance of the class is created.

Every time when an object of a class is created, then a constructor which is a member function is automatically called and every object is carried out by a special class function which is known as a constructor. Every time when an object is created, the compiler invokes the constructor. Constructors assign or initialize values mainly to the object members just after the storage has been allocated to the object.

How to create a constructor in C++?

In C++, a  constructor is a special method that will be automatically called whenever a class object has been created.

Syntax

Use parentheses () after the class name when creating a constructor.

(list-of-parameters);

It is possible to define constructors both inside and outside the class declaration: -

The following is the syntax for specifying the constructor within the class:

(list-of-parameters) { // constructor definition }

The following is the syntax for specifying the constructor outside of the class:

: : (list-of-parameters){ // constructor definition}

Example 1: program which defines the constructor within the class


#include <iostream>
using namespace std;

class student {
    int rno;
    char name[20];
    double fee;

public:
    student()
    {
        cout << "please enter the RollNo:";
        cin >> rno;
        cout << "Please enter the Name:";
        cin >> name;
        cout << "Please enter the Fee:";
        cin >> fee;
    }

    void display()
    {
        cout << endl << rno << "\t" << name << "\t" << fee;
    }
};

int main()
{
    student s; // automatically constructor will be called when
            // we create  object of the class
    s.display();

    return 0;
}

Output:

please enter the RollNo:25
Please enter the Name:John
Please enter the Fee:10000
25    John    10000

Example 2: program which defines the constructor outside of the class


#include <iostream>

using namespace std;
class student {
  int rno;
  char name[50];
  double fee;

  public:
    student();
  void display();
};

student::student() {
  cout << " Please Enter the RollNo:";
  cin >> rno;

  cout << "Please Enter the Name:";
  cin >> name;

  cout << "Please Enter the Fee:";
  cin >> fee;
}

void student::display() {
  cout << endl << rno << "\t" << name << "\t" << fee;
}

int main() {
  student s;
  s.display();

  return 0;
}

Output:

Please Enter the RollNo:12
Please Enter the Name:James
Please Enter the Fee:12000
12    James    12000

Example 3: a simple C++ program to understand the use of constructors

#include <iostream>
using namespace std;

class MyClass {     // The class
  public:           //Is the access specifier
    MyClass() {     // Constructor
      cout << "Hello Students!";
    }
};

int main() {
  MyClass myObj; //Create an object of MyClass (so this will surely call the constructor)
  return 0;
}

Output:

Hello Students!

Here in the above example the constructor it is having the same name as the class, it is public, as well as it does not have any kind of return value.

What distinguishes constructors from a typical/normal member function?

The following are some ways that constructors differ from regular/normal functions:

  • The constructor has the same name as the class.
  • Return types do not exist for constructors.
  • When an object is created, then a constructor will be invoked automatically.
  • If we don't specify a constructor, the C++ compiler creates a default constructor for us.

For an example


class  A {
   public:

    // constructor
    A() {
        // object initialization
    }
};
 

In this case, class A's constructer is represented by the function A().

It should be noted that the creator:

  • it has the same name as the class
  • it has no return type it is public

Different types of constructors in C++

There are three different categories of constructors:

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
C++ Constructors

Let's use a practical example to better understand the different types of constructors in C++.

Imagine you visited a store to purchase a bag. What possibilities are available when you wish to purchase a bag? The first time, you ask for a bag at a store. Giving me a bag means that you haven't specified the brand name or color; all you said was that you wanted a bag. Therefore, if we simply said, "I want a bag," he would bring us whatever the most popular bag was in the market or in his store and a default constructor is exactly the same.

The second option is to go into a store and specify that you want a bag of blue color from the ABC brand. So you mention it, and he gives you the bag. You have thus specified the parameters in this instance. And a parameterized constructor is just that!

The third one is when you visit a store and declare, "I want a bag just like this" (a physical bag in your hand). Thus, the store owner will notice that bag and he'll give you a new bag. Then an exact copy of that bag will be given by the shopkeeper. And a copy constructor is just that!

1.    Default Constructor

The constructor that doesn't accept any arguments is known as the default constructor. It has zero parameters. It is mainly called when the object is created.

Syntax

class_name ( ) ; .................................................    (1)    
class_name :: class_name ( ) body...................    (2)    
class_name() = delete ;......................................    (3)    
class_name() = default ;....................................    (4)    
class_name :: class_name ( ) = default ;..........    (5)
  1. class_name ( ): In the class definition, a default constructor is declared.
  2. class_name:: class_name ( ) body: The constructor is defined outside of the class definition (the class must have a declaration. For more information on the constructor body, check constructors as well as member initializer lists.
  3. class_name() = delete: The program cannot be compiled if the default constructor was deleted and was chosen via overload resolution.
  4. class_name() = default (Defaulted default constructors): even if other constructors are present, the compiler will specify the implicit default constructor.
  5. class_name:: class_name ( ) = default: When default initializations and value initializations occur, default constructors are called.

Example 1: A program is written in C++ to show how to use the Default Constructor.

#include <iostream>  
using namespace std;  
class Employee  
 {  
   public:  
        Employee()    
        {    
            cout<<"Default Constructor Is Invoked"<<endl;    
        }    
};  
int main(void)   
{  
    Employee e1; //creating an object of an Employee   
    Employee e2;   
    return 0;  
}

Output:

Default Constructor Is Invoked 
Default Constructor Is Invoked

Let us write a C++ program in order to understand the concept of the default constructer.


#include <iostream>
using namespace std;

class construct {
public:
    int a, b;

    // Default Constructor
    construct()
    {
        a = 80;
        b = 100;
    }
};

int main()
{
    // Default constructor will be  called automatically
    // when an object is created
    construct c;
    cout << "a: " << c.a << endl << "b: " << c.b;
    return 1;
}

Output:

a: 80
b: 100

2. Parameterized Constructor

The arguments can be passed to the constructors. When an object is formed, these arguments will typically help in initializing it. In order to make a parameterized constructor, simply add parameters to it as you would do for any other function. You should initialize the object using the parameters when defining the constructor's body.

Let us write a C++ program in order to understand the concept of the parameterized constructer.


#include <iostream>
using namespace std;

class Point {
private:
    int x, y;

public:
    // Parameterized Constructor
    Point(int x1, int y1)
    {
        x = x1;
        y = y1;
    }

    int getX() { return x; }
    int getY() { return y; }
};

int main()
{
    // Constructor called
    Point p1(100, 105);

    // Access the  values assigned by a constructor
    cout << "p1.x = " << p1.getX()
        << ", p1.y = " << p1.getY();

    return 0;
}

Output:

p1.x = 100, p1.y = 105

What are the uses of Parameterized constructor?

  • When creating new objects, it is used to initialize the various data elements with new values.
  • Overloading the constructor is a function of it.

In this tutorial, we have explained C++ constructors and types of constructors with suitable examples. The copy constructor is also a type of constructor that will be explained in the next tutorial.