LOGBOOK

HELP

Quiz Entry - updated: 2026.07.06

How do you define a method outside the class declaration?

Use the scope-resolution operator: ReturnType ClassName::method() { … }.

// In the header / class declaration
class Vehicle {
public:
    void show() const;
    int  getNWheels() const;   // helpers that show() delegates to
private:
    virtual string getName();  // each subclass overrides this
};

// In the .cpp file (the definition)
void Vehicle::show() const {
    cout << getName() << " has " << getNWheels() << " wheels." << endl;
}

Key points:

  • :: is the scope resolution operatorVehicle::show means "the show belonging to Vehicle"
  • A trailing const after () repeats the promise from the declaration that the method won't modify the object
  • The out-of-class definition can freely call the class's other members — here show() delegates to getName() and getNWheels() rather than touching the fields directly
  • Because getName() is virtual, a Truck printing through this same show() reports "Truck has …" — the base method automatically calls the subclass's name

Tip: Splitting declaration (header) from definition (.cpp) is the normal C++ pattern — it lets many files share the class while it's compiled once.

From Quiz: REVE1 / C++ Programming | Updated: Jul 06, 2026