Suprapunerea functiilor - function overriding

Suprapunerea functiilor inseamna schimbarea implementarii unei clase intr-o clasa derivata. Exemplul urmator ilustreaza suprapunerea functiilor

//suprapunerea functiilor
#include <iostream.h>

class Mamifer
{
public:
Mamifer():varsta(1) { cout << "Mamifer constructor...\n"; }
~Mamifer() { cout << "Mamifer destructor...\n"; }
void Speak() const { cout << "Mamifer speak!\n"; }
protected:
int varsta;
};

class Dog : public Mamifer
{
public:
Dog() { cout << "Dog Constructor...\n"; }
~Dog() { cout << "Dog destructor...\n"; }
void Speak()const { cout << "Ham!\n"; }
};

class CatDog : public Dog
{
public:
CatDog() { cout << "pisi constructor...\n"; }
~CatDog() { cout << "pisi destructor...\n"; }
void Speak()const { cout << "Miau!\n"; }
};

int main()
{

Mamifer *pDog = new Dog;    //1
CatDog pisi;                //2
Dog *pPisi = new CatDog;    //3
pDog->Speak();              //4
pisi.Speak();               //5
pPisi->Speak();             //6
delete pPisi;               //7
return 0;                   //8

}

Dupa rulare la fisierul standard de iesire se obtine

Mamifer constructor...
Dog Constructor...

dupa linia 1

Mamifer constructor...
Dog Constructor...
pisi constructor...

dupa linia 2

Mamifer constructor...
Dog Constructor...
pisi constructor...

dupa linia 3

Mamifer speak! dupa linia 4
Miau!         
dupa linia 5
Ham!          
dupa linia 6
Dog destructor...
Mamifer destructor...

dupa linia 7
pisi destructor...
Dog destructor...
Mamifer destructor...

la iesirea din program sunt sterse obiectele create fara operatorul new (aici pisi).

Cornel Mironel Niculae, 2003-2004

11-Mar-2004