Wednesday, November 21, 2007

Constructors in C++

A constructor in c++ programming language is a function that initializes the members of an object. A constructor only knows how to construct an object of its own class.
Constructors are not automatically inherited between base and the derived classes. If you don't give one in the derived class, a default will be supplied but this may not do what you want.

If we don’t use constructor then a default one is created by the compiler not including any parameters. There must always be a constructor, though it is the default and empty. If you provide a constructor with parameters then a default will not be created.

Some points about constructors to remember

1. Constructors are just functions with the same name as the class.
2. Constructors are intended to initialize the members of the class when an instance or the object of that class is created.
3. Constructors are not called directly (except for through initializer lists)
4. Constructors will not be virtual.
5. Multiple constructors for the similar class can be defined. They must have different parameters to differentiate them.

No comments: