Default Constructors in C++


Constructors are functions of a class that are executed when new objects of the class are created. The constructors have the same name as the class and no return type, not even void. They are primarily useful for providing initial values for variables of the class. The two main types of constructors are default constructors and parameterized constructors.

Default constructors do not take any parameters. If a default constructor is not provided by the programmer explicitly, then the compiler provides a implicit default constructor. In that case, the default values of the variables are 0.

A program that demonstrates default constructors is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
class DemoDC {
   private:
   int num1, num2 ;
   public:
   DemoDC() {
      num1 = 10;
      num2 = 20;
   }
   void display() {
      cout<<"num1 = "<< num1 <<endl;
      cout<<"num2 = "<< num2 <<endl;
   }
};
int main() {
   DemoDC obj;
   obj.display();
   return 0;
}

Output

num1 = 10
num2 = 20

In the above program, the class DemoDC contains a default constructor that initialises num1 and num2 as 10 and 20. It also contains a function display() that prints the value of num1 and num2. The code snippet for this is given as follows.

class DemoDC {
   private:
   int num1, num2
   public:
   DemoDC() {
      num1 = 10;
      num2 = 20;
   }
   void display() {
      cout<<"num1 = "<< num1 <<endl;
      cout<<"num2 = "<< num2 <<endl;
   }
};

The function main() contains the object definition for an object of class type DemoDC. Then the function display() is called. This is shown below.

DemoDC obj;
obj.display();

Updated on: 24-Jun-2020

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements