Sams Teach Yourself C++ in 21 Days

(singke) #1
Implementing Inheritance 397

12


access it in the same way you have been using the base class to access the virtual meth-
ods? There shouldn’t be a name conflict because only the derived class has the method.
If the Dogobject had a method,WagTail(), which is not in Mammal, you could not use the
pointer to Mammalto access that method. Because WagTail()is not a virtual function,
and because it is not in a Mammalobject, you can’t get there without either a Dogobject or
a Dogpointer.
You could cast the Mammalto act as a Dog; however, this is not safe if the Mammalis not a
Dog. Although this would transform the Mammalpointer into a Dogpointer, a much better
and safer way exists to call the WagTail()method. Besides, C++ frowns on explicit casts
because they are error-prone. This subject is addressed in depth when multiple inheri-
tance is covered on Day 15, and again when templates are covered on Day 20, “Handling
Errors and Exceptions.”

Slicing ............................................................................................................


Note that the virtual function magic operates only on pointers and references. Passing an
object by value does not enable the virtual functions to be invoked. Listing 12.10 illus-
trates this problem.

LISTING12.10 Data Slicing When Passing by Value


1: //Listing 12.10 Data slicing with passing by value
2: #include <iostream>
3: using namespace std;
4:
5: class Mammal
6: {
7: public:
8: Mammal():itsAge(1) { }
9: virtual ~Mammal() { }
10: virtual void Speak() const { cout << “Mammal speak!\n”; }
11:
12: protected:
13: int itsAge;
14: };
15:
16: class Dog : public Mammal
17: {
18: public:
19: void Speak()const { cout << “Woof!\n”; }
20: };
21:
22: class Cat : public Mammal
23: {
24: public:
Free download pdf