Constructors and its Types
Constructors and its Types
A constructor is a member function with the same name as its class. Constructor does not have a return type and a return statement in the body of a constructor cannot have a return value. Constructor cannot be declared as virtual or static, nor can it be declared as const, volatile, or const volatile.
Example,
class ABC
{
public:
ABC (); // Constructor of class ABC
}
Types of Constructors:
1. Parameterized Constructors.
2. Default Constructors.
3. Copy Constructors.
The Constructors that can take arguments are called Parameterized Constructors, e.g.
class ABC {
int a, b;
public:
ABC(int i, int j) {
a=i;
b=j;
}
void show() {
cout << a << " " << b;
}
};
int main()
{
ABC ob(3, 5);
ob.show();
return 0;
}
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.
A copy constructor is a special constructor which is used to create a new object as a copy of an existing object.
class ABC {
public:
ABC(); // default constructor, no arguments
X(int, int , int = 0); // constructor
X(const X&); // copy constructor
};
class Y {
public:
Y( int = 0); // default constructor with one and default argument
Y(const Y&, int = 0); // default argument and copy constructor
};
Posted in Computer Science, Information Technology, Object Oriented Programming, Object Oriented Programming |
