June 2025
Intermediate to advanced
1093 pages
33h 24m
English
In other languages, this is sometimes different: if you had written the preceding listing (with obvious changes for the language) in Java, then you would have seen a 10 at Value va{}; va.print(cout) as Java checks at runtime which methods are available to an instance.
And because this is also a reasonable behavior (otherwise it would hardly have been chosen as the default behavior in Java), it is also possible in C++. The key to this is virtual methods.
If you mark a method with the virtual keyword, the compiler decides at runtime which version of this method is valid. And thus you get the Java behavior.
// https://godbolt.org/z/vW5s3Kh6M#include <iostream>using std::ostream; using std::cout;struct Base2 { int eight_ ...
Read now
Unlock full access