-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinheritance.cpp
83 lines (71 loc) · 1.53 KB
/
inheritance.cpp
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
using namespace std;
// Base class
class Animal {
public:
// Virtual function
virtual void makeSound() {
cout << "The animal makes a sound." << endl;
}
};
// Derived class from Animal
class Dog :
public Animal {
public:
// Override the makeSound function
void makeSound() {
cout << "The dog barks." << endl;
}
};
// Derived class from Animal
class Cat : public Animal {
public:
// Override the makeSound function
void makeSound() {
cout << "The cat meows." << endl;
}
};
// Multiple inheritance example
// Base class 1
class Printable {
public:
// Virtual function
virtual void print() {
cout << "Printing the object..." << endl;
}
};
// Base class 2
class Drawable {
public:
// Virtual function to draw the object
virtual void draw() {
cout << "Drawing the object..." << endl;
}
};
// Derived class from Printable and Drawable
class Shape : public Printable, public Drawable {
public:
// Override the print and draw functions
void print() {
cout << "Printing the shape..." << endl;
}
void draw() {
cout << "Drawing the shape..." << endl;
}
};
int main() {
// Single inheritance
Dog dog;
Cat cat;
Animal* animal1 = &dog;
Animal* animal2 = &cat;
animal1->makeSound();
animal2->makeSound();
// Multiple inheritance
Shape shape;
Printable* printable = &shape;
Drawable* drawable = &shape;
printable->print();
drawable->draw();
return 0;
}