Constructor
In class-based object-oriented programming, a constructor is a special type of subroutine called to create an object.
Is a special kind of method that specifies one possible construction recipe for a new instance of the class.
In C++
This is how a object is actually created:
- Space is allocated
- Call the superclass constructor
- Initialize fields via a member initialization list (MIL)
- Run the constructor body
Compiler-Provided Constructor
If you do not write any constructors at all, you get a compiler provided default constuctor:
- Primitive fields are uninitialized (garbage values)
- Object fields are default constructed, see Initialization
If you write any constructor yourself, the compiler provided constructor is not supplied.
How does the compiler ACTUALLY know how much space to allocated?
This is related to the vptr question, that I messed up on the midterm.
It calls the parent class for example. And what if the parent class is actually a pure virtual function? Well it knows how much space the parent class needs, because there is a declaration on the methods and variables. Stackoverflow: https://stackoverflow.com/questions/36129281/c-how-does-the-compiler-know-how-much-memory-to-allocate-for-each-stack-frame
The constructor has the same name as the Class name.
IMPORTANT: Always Use Member Initialization Lists
Idiom to AVOID in C++
In Java and Python, in the constructor, we like to do:
self.total = total
orthis->total = total
but this is something to avoid in C++.In C++, we have a cleaner way of doing things using Initializer.
There are cases where using the MIL is necessary
There are 4 cases where initialization certain types of fields in the constructor body does not work:
- Initializing
const
fields- Initializing reference fields
- Object fields without default constructors
- If the superclass doesn’t have a default constructor
Const
fields
- Reference fields
- Object fields without default constructors
- If the superclass does not have a default constructor
What if we gave A a default constructor?
Correct way:
- This works even if A does not have a default constructor!
Constructor with Default Arguments
We don’t need to write different constructors for a different number of arguments. We can just use default parameters!
Default parameters MUST be trailing
Something like
Foo(string x="hello", int y)
won’t compile because of ambiguity issues. imagine there is another constructorFoo(int z)
and callingFoo{5}
. We wouldn’t know which constructor to use.
Additionally, default parameters must only appear in the Declaration, not the Definition.
Example of Constructor and Inheritance
I also have this example in Inheritance, this is how constructors are done with inheritance.
Constructor Overloading
This is when we have multiple constructor definitions, which differ in the parameters they take.
In Python
The constructor is called