Start learning free

LESSON 606 OF 634 · OBJECT-ORIENTED PROGRAMMING

Printing Objects in C++ in C++

Lesson

TL ; DR:

Write an operator<< function for your class. Then cout << can print its objects.


class Cat {
public:
    string name;
    Cat(string name) {
        this->name = name;
    }
};

ostream& operator<<(ostream& out, const Cat& cat) {
    out << "Cat named " << cat.name;
    return out;
}

// cout << Cat("Tom") << endl;   prints Cat named Tom


Full lesson:

cout << knows how to print numbers and strings. It doesn't know your classes. So cout << tom doesn't even compile:

error: no match for 'operator<<'

In C++, << is a function named operator<<. You can add one more version of it, for your class. This is called operator overloading.

Your version takes the stream as ostream& out and the object as const Cat& cat. The & passes both without copying them. The const promises not to change the cat.

Inside, send the parts to out with <<, as you would to cout. Then return out. That lets the caller keep chaining, as in cout << tom << endl.

It works for every output stream, files too. It sits outside the class, so it reads public fields. For private fields, declare it a friend inside the class.


Your task

The Dog class below has a name and an age. Below the class, write operator<< for Dog.

It sends the name, then " is ", the age and " years old". The code in mainFunction prints two dogs.

Expected output:

Rex is 3 years old
Bella is 5 years old
STEP 1 OF 3
    Ctrl + Enter to check

    Printing Objects in C++

    Keep going with C++500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free