FAQ 17.02 How does C++ express inheritance?
#include <iostream> using namespace std; class Vehicle { public: virtual void startEngine() throw() = 0; virtual ~Vehicle() throw(); }; Vehicle::~Vehicle() throw() { } class V8Engine { public: void start() throw(); }; void V8Engine::start() throw() { cout << "starting V8Engine\n"; } class Car : public Vehicle { public: virtual void startEngine() throw(); protected: V8Engine engine_; }; void Car::startEngine() throw() { engine_.start(); } This relationship can be described in several equivalent ways.
As a consequence of the kind-of relationship, a Car object can be treated as a Vehicle object. For example, since function f(Vehicle&) accepts any kind-of Vehicle, it can be passed a Car or an object of any other class derived from Vehicle: void f(Vehicle& v) throw() { v.startEngine(); } int main() { Car c; f(c); } UML uses the following notation to show inheritance. |