Constructors in C++ Programming


In this tutorial, we will be discussing a program to understand constructors in C++.

Constructors are member functions of the classes which initiates the object instance creation. They have the same name as the parent class and don’t have any return type.

Default constructors

Example

 Live Demo

#include <iostream>
using namespace std;
class construct {
   public:
   int a, b;
   //default constructor
   construct(){
      a = 10;
      b = 20;
   }
};
int main(){
   construct c;
   cout << "a: " << c.a << endl
   << "b: " << c.b;
   return 1;
}

Output

a: 10
b: 20

Parameterized constructors

Example

 Live Demo

#include <iostream>
using namespace std;
class Point {
   private:
   int x, y;
   public:
   Point(int x1, int y1){
      x = x1;
      y = y1;
   }
   int getX(){
      return x;
   }
   int getY(){
      return y;
   }
};
int main(){
   Point p1(10, 15);
   cout << "p1.x = " << p1.getX() << ", p1.y = " <<
   p1.getY();
   return 0;
}

Output

p1.x = 10, p1.y = 15

Updated on: 12-Mar-2020

415 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements