CodeBlanks Logo Icon CodeBlanks

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.

Practice 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().

Starter code

main.cpp
#include <iostream>

// Define Animal and Dog classes here

int main() {
    // Create Dog, call speak via Animal*
    return 0;
}

Sample solution

main.cpp
#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;
}

Expected output

Woof

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the virtual keyword

Question
class Animal { public: ____ void speak() { } };
Answer
class Animal { public: virtual void speak() { } };

Explanation: virtual lets speak be redefined in a derived class.

2 What does Animal* a = &dog; a->speak(); print? (speak is virtual, Dog::speak prints "Woof")

main.cpp
Animal* a = &dog;
a->speak();
  • Sound
  • Compile error
  • Nothing
  • Woof Correct answer

Explanation: With virtual, the real type of dog is chosen and Woof is printed.

3 Match each piece to its role

Term Meaning
virtual Enables polymorphism
-> Member access via pointer
Animal* Base class pointer
&dog Object the pointer points to

All lessons in Intermediate