Thursday, 20 January 2022

Parameterized Constructor in C++

 Whenever we want to initialize data members with some values we use parameterized constructors.


#include<iostream.h>

#include<conio.h>

class abc

{

int a,b;

public:

abc()//default

{

a=0;

b=0;

}

abc(int x,int y)//parameterized

{

a=x;

b=y;

}

void show()

{

cout<<"a= "<<a<<endl<<"b= "<<b<<endl;

}

};

void main()

{

clrscr();

abc ob1,ob2(10,20);

ob1.show();//it will print 0 0

ob2.show();//it will print 10 20

getch();

a & b of ob1 will be initialized to 0

a & b of ob2 will be initialized to 10  &  20 respectively.

Note: As we are creating a parameterized constructor we always need to provide default constructor.



Default Constructor

Parameterized Constructor

Copy Constructor

Dynamic Constructor

No comments:

Post a Comment