Constructor And Types Of Constructor

constructor
constructor

Constructor:-

Constructor  is a special member function. It has the same name as that of its class in which it is declared.

This is  used to initialize the properties of a class in which, it is a member function.

It called automatically whenever an object of a class is created. It does not have any return type. This can not be  void also .

We can do many things nicely with the help of this special function. Its nice to use.

Syntax,

class <class name>

{

…………………………..

public:

<classname>(parameters)

…………………………………………

…………………………………………

};

<classname>::<classname> (parameter)

{

…………………………………………………….

……………………………………………………..

}

Example,

#include<iostream.h>

#include<conio.h>

class square

{

int side;

public:

square ()

{

side = 5;

}

int area ()

{return (side*side);

} };

void main ()

{

clrscr ();

square s1;

cout<<”  Area of a square: – “ <<s1 area ();

getch ();

}

output,

Area of a square: – 25

 

There are following type of constructors,

Default:-

A constructor in which no arguments are passed is known as default constructor.

When we does not define any constructor then compiler automatically call a constructor of its own with no arguments. This type of constructor does not do any initialization, since we explicitly didn’t define any constructor with initialization of properties of class.

Parameterized:-

constructor which take parameters is called parameterized constructor.

With the help of, this type of function we can give any value to a variable  when objects of that class is created.

Example,

#include<iostream.h>

#include<conio.h>

class square

{

int side;

public:

square (int x)

{

side = x;

}

int area ()

{return (side*side);

} };

void main ()

{

clrscr ();

square s1(5);

cout<<”  Area of a square: – “ <<s1.area ();

getch ();

}

Output,

Area of a square: – 25

You Also Can Visit For More Knowledge In C++:-

Visit Your YouTube  Channel:-  Think , About It

Visit Your Website :- www.atozlives.com

Thanks,

“Play With All Computer Science , Mathematics  And Technology.”

 

 

3 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here