Advertisements
Advertisements
Question
What is a constructor in C++?
Code Writing
Long Answer
Advertisements
Solution
A constructor is a special member function of a class. Its task is to initialise the objects of its class.
It is special because its name is the 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 a constructor because it constructs the values of data 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;
}shaalaa.com
Is there an error in this question or solution?
2018-2019 (March) Set 1
