virtual — see the Polymorphism pageclass Animal
{
public:
void speak() { cout << "Some sound\n"; }
};
class Dog : public Animal
{
public:
void speak() { cout << "Bark!\n"; } // overrides Animal::speak()
};
Dog d;
d.speak(); // "Bark!" -- Dog's version is used
| Overloading | Overriding | |
|---|---|---|
| Where | Same class (or same scope) | Base class vs derived class |
| Signature | MUST differ (params/types) | MUST be identical |
| Resolved | Compile-time | Runtime (if virtual) or compile-time (if not) |
| Purpose | Same operation, different input types | Same operation, specialized for a subclass |
class Printer
{
public:
void print(int x) { cout << "int: " << x; } // OVERLOADING --
void print(string s) { cout << "string: " << s; } // -- same class, different signatures
};
class Animal
{
public:
void speak() { cout << "Some sound\n"; }
};
class Dog : public Animal
{
public:
void speak() { cout << "Bark!\n"; } // OVERRIDING -- same signature, different class
};
virtual — the trapclass Animal { public: void speak() { cout << "Some sound\n"; } };
class Dog : public Animal { public: void speak() { cout << "Bark!\n"; } };
Animal* a = new Dog();
a->speak(); // prints "Some sound" -- NOT "Bark!" -- because speak() isn't virtual, static binding applies
Without virtual, the compiler decides which speak() to call based on the pointer's declared type (Animal*), not the actual object type (Dog). This is called static binding, and it's the #1 reason overriding "doesn't work" for students — see the Virtual Function page for the fix.
virtual keyword on the base method, calling it through a base-class pointer to a derived object uses:
a->speak() print "Some sound" instead of "Bark!"?2026, Paper I, Q4(c) (8 marks) — Demonstrate method overriding using a base class Account and a derived class Current Account. Make balance a protected data member.