Start learning free

LESSON 277 OF 667 · FUNCTIONS & CLASSES

Constructors in C++

Lesson

TL ; DR:

  • A constructor is a special method that runs automatically when you create an object. It's used to set up the object's initial state.


  • In C++, a constructor has the same name as the class and no return type:

    class Dog {
    public:
        string name;
        int age;
    
        Dog(string name, int age) {
            this->name = name;
            this->age = age;
        }
    };
    

  • Then create objects with arguments: Dog rex("Rex", 4); — the constructor fills in the members for you.



Full lesson:

In the previous lesson you set member variables one at a time after creating the object:

Dog dog;
dog.name = "Rex";
dog.age = 4;

That works, but it's verbose and easy to forget. Constructors let you initialize the members the moment the object is created.


Defining a constructor

A C++ constructor has two distinguishing features:

  • Its name is exactly the class name (Dog for a Dog class).

  • It has no return type — not even void.

Dog(string name, int age) {
    this->name = name;
    this->age = age;
}

The this pointer

The parameter name and the member name have the same identifier. C++ uses this->name (arrow operator, because this is a pointer) to refer to the member, and bare name for the parameter.


Calling the constructor

Dog rex("Rex", 4);
Dog luna("Luna", 7);

By the time these lines finish, rex.name is already "Rex", rex.age is 4, and the same for Luna. Note: no new is needed when creating stack-allocated objects.


Your task

The Dog class already has the name and age members. Add a constructor that takes a string name and an int age and assigns them using this->. Then in mainFunction, create two dogs:

Dog rex("Rex", 4);
Dog luna("Luna", 7);

Expected output:

Rex is 4
Luna is 7
STEP 1 OF 2
    Ctrl + Enter to check