What is a constructor?
Invoking a C++ Constructor
A constructor is invoked when its associated class is used in a definition. Not all declarations are definitions. A constructor is not invoked when the class is used in a declaration that is not a definition.
If we have a class foo
, then
foo y(3);
invokes the foo()
constructor, while
extern foo x;
does not invokes the foo()
constructor.
Constructor function in C++
The class designer can guarantee initialization of every object by providing a special function called the constructor. If a class has a constructor, the compiler automatically calls that constructor at the point an object is created, before client
programmers can get their hands on the object. The constructor call is not even an option for the client programmer; it is performed by the compiler at the point the object is defined. The next challenge is what to name this function. There are two issues.
- The first is that any name you use is something that can potentially clash with a name you might like to use as a member in the class.
- The second is that because the compiler is responsible for calling the constructor, it must always know which function to call.
The solution Stroustrup chose seems the easiest and most logical: the name of the constructor is the same as the name of the class. It
makes sense that such a function will be called automatically on initialization. Here is a simple class with a constructor:
class X {
int i;
public:
X(); // Constructor
};
Now, when an object is defined,
void f() {
X a;
// ...
}
the same thing happens as if a were an int: storage is allocated for the object. But when the program reaches the sequence point (point of execution) where a is defined, the constructor is called automatically. That is, the compiler quietly inserts the call to X::X( ) for the object a at the point of definition. Like any member function, the first argument to the constructor is the this pointer (the address of the object for which it is being called). In the case of the constructor, however, this is pointing to an un-initialized block of memory, and it is the job of the constructor to initialize this memory properly.
Like any function, the constructor can have arguments to allow you to specify how an object is created, give it initialization values, and so on. Constructor arguments provide you with a way to guarantee that all parts of your object
are initialized to appropriate values. For example, if a class Tree has a constructor that takes a single integer argument denoting the height of the tree, then you must create a tree object like this:
Tree t(12); // 12-foot tree
If Tree(int) is your only constructor, the compiler will not let you create an object any other way.