CONSTRUCTORS
Why do we need Constructors?
giving the default values cannot be done outside the class. Array can be initialized at the time of the declaration but class is different. It's private members are not accessible outside the class. So there is a need of constructors which can initialize the values to the variables if no values are given to them.Example:
class A
{
private:
int a;
int b;
public:
A() //This is called Default Constructor
{
a=1;
b=1;
}
};
void main()
{
clrscr();
A obj; //Object created
getch();
}
As soon as the Object is created the private members 'a' and 'b' are initialized. This makes the initialization easy because earlier we have to declare another function for initializing but constructor made that easy.
No comments:
Post a Comment