C++ Default constructor

Default constructor is a constructor without any parameter. And default constructor is implemented in two ways:

a.      Implicit default constructor

b.      Explicit default constructor    

a. Implicit default constructor: An implicit constructor that are added by java compiler itself and we don’t need to explicitly specified or define the constructor.

 

e.g:     

class Rectangle()

{

int length;

int breadth;

public:

int area()

{

return(length*breadth);

}

}

void main()

{

Rectangle r1=new Rectangle();         //object created using implicit constructor

cout<<“area of rectangle r1=”<<r1.area();

}

b. Explicit default constructor: explicit constructor which are use to define by the user to explicitly specify or initialize the data members of the class once we define a constructor in a class it overwrites the functionality of default implicit function.

e.g:     

class Rectangle()

{

int length;

int breadth;

public:

Rectangle()

{

length=20;

breadth=30;

}

int area()

{

return(length*breadth);

}

}

void main()

{

Rectangle R1=new Rectangle();                 //object created using implicit constructor

cout<<“area of rectangle R1=”<<R1.area();

}

Leave a Reply

Your email address will not be published. Required fields are marked *