Back to questions
JuniorTheoryCommon
What happens when you build and run this program?
#include <iostream>
struct Base {
virtual void print(int x) const { std::cout << "Base " << x; }
};
struct Derived : public Base {
void print(long x) const override { std::cout << "Derived " << x; }
};
int main() { Derived d; const Base& b = d; b.print(1); }It does not compile: print(long) overrides nothing in Base
- Expecting
Base 1: the compiler checksoverride; a function marked with it must override a virtual function of a base class, or the program does not compile. - Expecting
Derived 1: an override needs the same parameter types, soprint(long)is a different function fromprint(int), even though1converts tolong.
- What would the program print if the word
overridewere removed? - Why is
finalsometimes written next tooverride?