C++
virtual
Learn virtual methods and polymorphism with virtual.
virtual
By marking a base class member function virtual, you let a derived class run its own version. This is called polymorphism. When called through a pointer or reference, the object's real type is used.
Example: class Animal { public: virtual void speak() { std::cout << "Sound"; } };. Dog redefines it: void speak() { std::cout << "Woof"; }. The call Animal* a = &dog; a->speak(); prints Woof, because with virtual the real type of dog is chosen. Without virtual, it would print Sound.
Calling through a pointer
Polymorphism happens at runtime; it requires a base class pointer or reference. A direct call through an object does not work, because the compiler uses the static type. The -> operator accesses a member through a pointer.
Example: Dog dog; Animal* a = &dog; a->speak();. Here a is an Animal pointer but points to the dog object. With virtual, Dog::speak is called. A reference works too: Animal& r = dog; r.speak();. Both give the same result.
Exercise Polymorphism with virtual speak
Define an Animal class: under public: virtual void speak() { std::cout << "Sound"; }. Derive Dog from Animal and redefine void speak() { std::cout << "Woof"; }. In main create Dog dog;, take Animal* a = &dog; and call a->speak().
Show example solution
#include <iostream>
class Animal {
public:
virtual void speak() {
std::cout << "Sound";
}
};
class Dog : public Animal {
public:
void speak() {
std::cout << "Woof";
}
};
int main() {
Dog dog;
Animal* a = &dog;
a->speak();
return 0;
}
Test yourself
-
Write the virtual keyword
class Animal { public: ____ void speak() { } };
Show answer
class Animal { public: virtual void speak() { } };
-
What does Animal* a = &dog; a->speak(); print? (speak is virtual, Dog::speak prints "Woof")
Animal* a = &dog;
a->speak();
- Sound
- Compile error
- Nothing
- Woof
Show answer
Woof — With virtual, the real type of dog is chosen and Woof is printed.
-
Match each piece to its role
- virtual
- Enables polymorphism
- ->
- Member access via pointer
- Animal*
- Base class pointer
- &dog
- Object the pointer points to
Next lesson: override