-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvirtual_functions_inheritance.cpp
More file actions
63 lines (52 loc) · 1.36 KB
/
virtual_functions_inheritance.cpp
File metadata and controls
63 lines (52 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <string>
using namespace std;
// All classes are not suitable for base classes
class Animal
{
public:
Animal (string nam = "Who am I ?"):name(nam)
{
}
virtual void eat () {cout << name << " is Eating \n";}
virtual void sleep () {cout << name << " is Sleeping \n";}
virtual void speak () {}
~Animal () {cout << "Destroying Animal \n";}
protected:
string name;
};
class Cat : public Animal
{
public:
Cat ():Animal("Cat") {}
// Over-rides the base implementation
void speak () {cout << "Meoow \n";}
~Cat () {cout << "Destroying cat \n";}
};
class Dog : public Animal
{
public:
Dog ():Animal("Dog") {}
void speak () {cout << name << ": Woof \n";}
~Dog () {cout << "Destroying Dog \n";}
};
class BullDog : public Dog
{
public:
BullDog () {name = "Bull Dog";}
void speak () {cout << name << ": Wrrrrrrrrroof \n";}
~BullDog () {cout << "Destroying Bull Dog \n";}
};
int main ()
{
Animal *doggy = new Dog ();
Animal *bullDoggy = new BullDog ();
// Note that after this point the client is independent of the derived classes. Derived classes depend on implementation details
doggy->speak ();
// Note that speak is not marked virtual in Dog class, but still BullDog functions is called.
bullDoggy->speak ();
// Am i deleting the whole object ? ;-)
delete doggy;
delete bullDoggy;
cout << "Bye Bye " << endl;
}