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