-
Notifications
You must be signed in to change notification settings - Fork 0
Polymorphism
Delton Hughes edited this page Apr 29, 2023
·
1 revision
Definition: The ability of objects of different classes to be treated as if they are of the same class, allowing for a single function call to have different behaviors depending on the type of object being used.
Code Example:
#include <iostream>
class Animal {
public:
virtual void makeSound() const = 0; // pure virtual function
};
class Dog : public Animal {
public:
virtual void makeSound() const override {
std::cout << "Woof!" << std::endl;
}
};
class Cat : public Animal {
public:
virtual void makeSound() const override {
std::cout << "Meow!" << std::endl;
}
};
int main() {
Animal* animalPtr = nullptr;
Dog dog;
Cat cat;
animalPtr = &dog;
animalPtr->makeSound(); // calls Dog's implementation of makeSound()
animalPtr = &cat;
animalPtr->makeSound(); // calls Cat's implementation of makeSound()
return 0;
}
- Each term will have as follows: -> A definition on the term -> A code example some being in great detail if needed, for example a class example is going to be longer than a member variable. -> Lastly, a picture which in some way relates to the term but may also relate to other terms as well.