-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleInheritance.cpp
More file actions
37 lines (30 loc) · 837 Bytes
/
SingleInheritance.cpp
File metadata and controls
37 lines (30 loc) · 837 Bytes
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
// Topic: Inheritance
// Standard: C++20
// Build: g++ -std=c++20 -o single_inheritance SingleInheritance.cpp
#include <iostream>
#include <string>
class Animal {
public:
void eat() const {
std::cout << "Animal is eating\n";
}
};
class Dog : public Animal {
public:
void bark() const {
std::cout << "Dog is barking\n";
}
};
int main() {
Dog dog;
dog.eat(); // inherited from Animal
dog.bark(); // Dog's own behavior
// Interview one-liner:
// Inheritance allows a derived class to reuse base class members and add its own behavior.
//
// Additional interview points:
// 1) Use inheritance only for true "is-a" relation.
// 2) If only behavior reuse is needed, prefer composition.
// 3) In polymorphic base classes, add virtual destructor.
return 0;
}