- It is a member function having the same name as it’s class and which is used to initialize the objects of that class type with a legal initial value.
- The compiler call's the constructor when an object is created.
- We can't define a constructor in the private section, we can define only it in the public section.
Characteristics of constructors
- A constructor takes the same name as the class name.
- We can define our own constructors.
- Automatically called when an object is created.
- No return type is specified for the constructor.
- Overloading of constructors is possible.
- They cannot be inherited.
- They cannot be static.
Defining a constructor
- The constructor can be defined inside the class and also outside the class.
Defining a constructor(Inside the class)
class class-name{
access label:
data members;
member functions;
class-name();//constructor
}
Example
class employee{
private:
int employee_id;
char name[20];
float salary;
public:
employee(){
employee_id=10;
strcpy(name, “ashok’’);
salary=5000;
}
void getdata();
}ob1,ob2;
Defining the constructor(Outside the class)
class-name::class-name
{
body of the constructor function;
}
Types of constructor
- Default Constructor
- Parameterized Constructor
- Copy Constructor
Default Constructor
- The constructor which has no arguments on it is known as default constructor.
- The default constructor is also known as a no-argument constructor.
Example
class creature{
private:
int yearofbirth;
public:
creature(){
cout<<"constructor called";
};
main(){
creature obj;
getch();
return 0;
}
Parameterized constructor
- A constructor that receives arguments/parameters, is called the parameterized constructor.
- We can pass arguments to the constructor when objects are created.
Example
class creature{
private:
int yearofbirth;
public:
creature(int year){
year=yearofbirth;
}
};
copy constructor
- A constructor that initializes an object using values of another object passed to it as the parameter, is called copy constructor.
- It creates a copy of the passed object.
Example
class abc{
int a;
float b;
public:
void fun();
abc(int x, float y){
a=x;
b=y;
}
abc(abc &dob){
a=dob.a;
b=dob.b;
}
};