Explain the type of constrcuors with the examples.
#include<iostream>
using namespace std;
/*A constructor is a special type of member function of a class which initializes
objects of a class. In C++, Constructor is automatically called when object
(instance of class) is created. It is special member function of the class
because it does not have any return type*/
//Types of Constructors
//1. Default Constructors : Default constructor is the constructor which
//doesn’t take any argument.It has no parameters.
class Person
{
int age;
public:
Person():age(18){}
void Display() { cout << age << endl; }
};
/*2. Parameterized Constructors: It is possible to pass arguments to constructors.
Typically, these arguments help initialize an object when it is created.
To create a parameterized constructor, simply add parameters to it the way
you would to any other function. When you define the constructor’s body,
use the parameters to initialize the object.*/
class Person2
{
int age;
public:
Person2(int _age) :age(_age) {}
void Display() { cout << age << endl; }
};
//3. Copy Constructor: A copy constructor is a member function which
//initializes an object using another object of the same class.
class Person3
{
int age;
public:
Person3(int _age) :age(_age) {}
Person3(Person3& p) :age(p.age) {}
void Display() { cout << age << endl; }
};
int main()
{
//1 - Default constructor
Person a;
a.Display();
//2 - Parametrized constructor
Person2 b(30);
b.Display();
//3 - Copy constructor
Person3 c(25);
Person3 d(c);
c.Display();
}
Comments
Leave a comment