Статичне і динамічне зв’язування

Створення похідних об’єктів, конструктор похідного класу, послідовність виклику конструкторів, ліквідація похідних об’єктів, деструктор похідного класу, послідовність виклику деструкторів

 

Наступний приклад дає вичерпну інформацію про порядок створення і ліквідації

об'єктів суперкласів і підкласів. Схема успадкувань зображена на малюнку.

 

 

// Хижак

class Predator

{

private:

string favoritePrey;

public:

Predator(const string& prey);

~Predator();

};

Predator::Predator(const string& prey):favoritePrey(prey)

{

cout << "Favorite prey: "

<< prey << "\n";

}

Predator::~Predator()

{

cout << "Predator destructor was called!\n\n";

}

 

 

// Пестун class Pet { private: string favoriteToy; public: Pet(const string& toy ); ~Pet(); }; Pet::Pet(const string& toy ):favoriteToy(toy) { cout << "Favorite toy: " << toy << "\n"; } Pet::~Pet() { cout << "Pet destructor was called!\n"; } // Кішка: Хижак, Пестун class Cat : public Predator, public Pet { private: short catID; static short lastCatID; public: Cat(const string& prey, const string& toy ); ~Cat(); static void ShowCurrentID(); }; Cat::Cat( const string& prey, const string& toy ) : Predator( prey ), Pet( toy ) { catID = ++lastCatID; cout << "catID: " << catID << "\n---------\n"; } Cat::~Cat() { cout << "Cat destructor called: catID = " << catID << "...\n"; } void Cat:: ShowCurrentID() { cout << "catID: " <<lastCatID <<"\n---------\n"; } short Cat::lastCatID = 0;

int main() { Cat TC( "Mice", "Ball of yarn" ); Cat:: ShowCurrentID() Cat Benny( "Crickets", "Bottle cap" ); Cat:: ShowCurrentID() Cat Meow( "Moths", "Spool of thread" ); Cat:: ShowCurrentID() return 0; } Favorite prey: Mice Favorite toy: Ball of yarn catID: 1 --------- Favorite prey: Crickets Favorite toy: Bottle cap catID: 2 --------- Favorite prey: Moths Favorite toy: Spool of thread catID: 3 --------- Cat destructor called: catID = 3... Pet destructor was called! Predator destructor was called!

Cat destructor called: catID = 2... Pet destructor was called! Predator destructor was called!

Cat destructor called: catID = 1... Pet destructor was called! Predator destructor was called!