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 operator —Vehicle::showmeans "theshowbelonging toVehicle"- A trailing
constafter()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 togetName()andgetNWheels()rather than touching the fields directly - Because
getName()isvirtual, aTruckprinting through this sameshow()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.