Introduction to OOP Chapter 11: Static and Dynamic Behavior: next previous audio real text

Method Binding in C++

C++ is the most complex language. Not only must the programmer use the virtual keyword, but true polymorphism only occurs with pointer or reference variables.

class Animal {
public:
	virtual void speak () { cout << "Animal Speak !\n"; }
	void reply () { cout << "Animal Reply !\n"; }
};

class Dog : public Animal {
public:
	virtual void speak () { cout << "woof !\n"; }
	void reply () { cout << "woof again!\n"; }
};

class Bird : public Animal {
public:
	virtual void speak () { cout << "tweet !\n"; }
};


	Animal * a;
	Dog * b = new Dog();
	b->speak();
woof !
	a  = b;
	a->speak();
woof !
	Bird c = new Bird();
	c->speak();
tweet !
	a = c;
	a->speak();
tweet !

Intro OOP, Chapter 11, Slide 13

We will see an explanation for the curious C++ semantics when we discuss memory management in the next chapter.