Advertisements
Advertisements
Question
What is a constructor in C++? State any four special characteristics of constructor function.
Solution
A constructor is a special member function of a class. Its task is to initialize the objects of its class.”
It is special because its name is same as that of the class to which it belongs.
The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values of date members of the class. A constructor can never return any value. Hence, it is written with no return type (even void is not written).
e.g. A constructor is declared and defined as follows
//class with constructor
class integer
{
private: int m, n; public: integer (void); //constructor declared
};
integer :: integer (void) //constructor definded
{
m =0;
n=0;
}
Speical characteristics of constructor function :
1) The constructor name is always same as the class name.
2) They do not have return types, not even void and therefore, they cannot return values.
3) They cannot be static or virtual.
4) They should be declared in public section.