A constructor is a special member function of a class that
is executed whenever we create new objects of that class. A
constructor will have exact same name as the class and it does not have any
return type at all, not even void. Constructors can be very useful for setting
initial values for certain member variables.
Following
example explains the concept of constructor:
class sample
{
private:
int a,b;
public:
sample()
{
cout<<"\nconstructor invoked\n";
a=10;
b=15;
}
void displaysum()
{
cout<<"sum=\t"<<a+b;
}
};
void main()
{
sample s;
s.displaysum();
getch();
}
There
are several forms in which a constructor can take its shape namely:
- Default Constructor
- Parameterized Constructors
- Copy constructor
- Dynamic constructor
Default Constructor:
This constructor has no arguments in it. Default Constructor is also called as no argument
constructor.
Example:
class creature
{
private:
int yearofBirth;
public:
creature()
{
cout<<“Contructor called";
}
};
int main()
{
creature obj;
getch();
return 0;
}
Parameterized Constructors:
A parameterized constructor is just one that has
parameters specified in it. We can pass the arguments to constructor function
when object are created. A constructor that can take arguments are called
parameterized constructors.
Example:
class Creature
{
private:
int yearOfBirth;
public:
Creature(int year) //Parameterized Constructor
{
yearOfBirth = year;
}
};
void main()
{
Creature C1(25); //Implicit calling
Creature C2 = Creature(35); //Explicit calling
}
No comments:
Post a Comment