Constructors
Definition
A constructor is a special method that specifies a construction recipe for the new instance of that class
C++
Example
class Balloon {
public:
Balloon();
Balloon(string colour);
virtual ~Balloon();
void speak() const;
private:
string colour;
};
// These are constructors
Balloon::Balloon() {
this->colour = "clear";
}
Balloon::Balloon(string colour) {
this->colour = colour;
}
Uniform Initialization
Example
class Balloon {
public:
Balloon();
Balloon(string colour);
virtual ~Balloon();
void speak() const;
private:
string colour;
};
// These are constructors
Balloon::Balloon: Balloon{"clear"} {} // Call the other constructor (constructor delegation)
Balloon::Balloon(string colour): colour{colour} {}
Default Constructor
Info
A default constructor is the constructor of a class which can be called with no carguments
- A default ctor may be defined by the programmer, and if none is given, the compiler will define one for you.
- The compiler's ctor is as follows:
- For all sub-parts that are class/structs, call their default ctors
- For all sub-parts that are primitives, the sub-part is created, but may not receive an initial value depending on how the object was instantiated
- If you define any ctor, then the compiler will not define a default ctor for you