-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample.cpp
More file actions
60 lines (50 loc) · 1.18 KB
/
Copy pathexample.cpp
File metadata and controls
60 lines (50 loc) · 1.18 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
#include <iostream>
#include <string>
#include <vector>
#include <memory>
template<typename T>
class Container {
private:
std::vector<T> elements;
public:
void add(const T& element) {
elements.push_back(element);
}
void print() const {
for (const auto& element : elements) {
std::cout << element << " ";
}
std::cout << std::endl;
}
};
class Animal {
protected:
std::string name;
public:
Animal(const std::string& n) : name(n) {}
virtual ~Animal() = default;
virtual void makeSound() const = 0;
};
class Dog : public Animal {
public:
Dog(const std::string& n) : Animal(n) {}
void makeSound() const override {
std::cout << name << " says: Woof!" << std::endl;
}
};
int main() {
// Template class usage
Container<int> numbers;
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.print();
// Smart pointers and polymorphism
std::vector<std::unique_ptr<Animal>> animals;
animals.push_back(std::make_unique<Dog>("Rex"));
animals.push_back(std::make_unique<Dog>("Max"));
for (const auto& animal : animals) {
animal->makeSound();
}
return 0;
}