In C++, the constructor of a class is a
special member function that is invoked automatically when an object of that class is created. The primary role of a constructor is to initialize the class's data members.
Typically, when we talk about a constructor being "invoked in a class," we are referring to the declaration and definition of the constructor within the class's definition.
Here's an example
class MyClass {
public:
MyClass() { // Constructor definition within the class definition
// Initialization code
}
};
In contrast, the term "invoked in a definition" is likely referring to the instantiation of an object of the class, which triggers the constructor.
For example:
MyClass obj; // Constructor invocation during object definition
In code above,
MyClass obj;
, we are defining an object named obj of type MyClass. This statement invokes the MyClass constructor, creating an instance of MyClass.
In summary, a constructor is defined within a class and invoked when an object of that class is defined. These are complementary aspects of how constructors function in C++, rather than contrasting scenarios.
The constructor must be defined within the class before it can be invoked by the definition (creation) of an object.
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
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: