Constructor is a special class member function that class has the same name as that of its class.It is used to initialize the value to data member of a objects.When the object is created.
{
private:
int length;
int breath;
public:
rectangle() // constructor
{
length=10;
breath=20;
}
void area()
{
int area=length*breath;
cout<<"Area="<<area;
}};
void main()
{
rectangle a1;
a1.area();
getch();
}
Output of this program:-
Area=200
{
private:
int length;
int breath;
public:
rectangle() // constructor
{
length=10;
breath=20;
}
void area()
{
int area=length*breath;
cout<<"Area="<<area;
}};
void main()
{
rectangle a1;
a1.area();
getch();
}
Output of this program:-
Area=200
Syntax:
Class Class_name
{
private:
data members;
--------------;
protected:
data members;
public:
data members;
public:
class_name(parameters list) //declare and define a constructor
{
-------;
-------;
}};
Properties of a Constructor
- Constructor name must be same as that of in class name.
- Constructor does not return any value even not void.
- Constructor is executed automically when object of a class is created.
- Constructor is used to initialize value to the data member of a object ate the time of in creation.
- Constructor must have public access specifier.
- Constructor cannot be static.
- Constructor cannot access its address.
- If no constructor is define that compiler will automically execute a default constructor.
- A program has multiple constructor having zero or more parameter that compiler are not execute default constructor.
{
private:
int length;
int breath;
public:
rectangle() // constructor
{
length=10;
breath=20;
}
void area()
{
int area=length*breath;
cout<<"Area="<<area;
}};
void main()
{
rectangle a1;
a1.area();
getch();
}
Output of this program:-
Area=200
Types of constructor
Default constructor
Default constructor is a constructor that does contain any argument it is also called constructor with no parameter.
Syntax:- Class class_name
{
access specifier:
Data members;
--------------;
public:
class_name() //default constructor
{
------------;
------------ ;
}}:
Example:- class rectangle{
private:
int length;
int breath;
public:
rectangle() // constructor
{
length=10;
breath=20;
}
void area()
{
int area=length*breath;
cout<<"Area="<<area;
}};
void main()
{
rectangle a1;
a1.area();
getch();
}
Output of this program:-
Area=200
Parameterized constructor
Parameterized constructor is a constructor that have one or more argument.The parameterized constructor is used to gave different value to data member of different object.
Syntax:- Class class_name
{
Data members;
---------------;
class_name(arguments) //passing one or more arguments
{
-------------;
-------------;
}};
Comments
Post a Comment