add some classes experiment
This commit is contained in:
parent
0b0c4cfdcb
commit
d45fdd153d
3 changed files with 43 additions and 0 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -14,3 +14,4 @@ accumulate
|
|||
object-lifetime
|
||||
shared_ptr
|
||||
casts
|
||||
classes
|
||||
|
|
|
@ -14,3 +14,4 @@ add_executable(accumulate accumulate.cpp)
|
|||
add_executable(object-lifetime object-lifetime.cpp)
|
||||
add_executable(shared_ptr shared_ptr.cpp)
|
||||
add_executable(casts casts.cpp)
|
||||
add_executable(classes classes.cpp)
|
||||
|
|
41
classes.cpp
Normal file
41
classes.cpp
Normal file
|
@ -0,0 +1,41 @@
|
|||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
class Animal {
|
||||
public:
|
||||
// Note: using *virtual* does the difference here!
|
||||
virtual void makeSound() {
|
||||
std::cout << "<generic animal sound>" << std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
class Cow : public Animal {
|
||||
public:
|
||||
void makeSound() {
|
||||
std::cout << "Mooh." << std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
class Cat : public Animal {
|
||||
public:
|
||||
void makeSound() {
|
||||
std::cout << "Meow?" << std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
Cat cat;
|
||||
Cow cow;
|
||||
|
||||
// Does nothing:
|
||||
std::vector<Animal> animals = { cat, cow };
|
||||
for (auto &a: animals) {
|
||||
a.makeSound();
|
||||
}
|
||||
|
||||
// Meow? Mooh.
|
||||
std::vector<Animal*> animalptrs = { &cat, &cow };
|
||||
for (auto &a: animalptrs) {
|
||||
a->makeSound();
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue