I'd expect when
foo is declared at school
D, although not marked virtual, then your following code would call the implementation of
D (no matter the dynamic kind of
D&lifier d = ... d.foo()
However, within the following program, that's not the situation. Can anybody explain this? Is a technique instantly virtual whether it overrides an online function?
#include <iostream> using namespace std class C class D : public C class E : public D int primary(int argc, char **argv) amplifier e = *new E D&lifier d = *static_cast<D*>(&e) d.foo() return
The output of the aforementioned program is:
Standard 10.3.2 (class.virtual) states:
If your virtual member function vf is declared inside a class Base as well as in a category Derived, derived directly or not directly from Base, an associate function vf with similar title and same parameter list as Base::vf is declared, then Derived::vf can also be virtual (whether it's so declared) also it overrides*
[Footnote: A function with similar title but another parameter list (clause over) like a virtual function isn't always virtual and doesn't override. Using the virtual specifier within the promise of an overriding function is legal but redundant (has empty semantics). Access control (clause class.access) isn't considered in identifying overriding. --- finish foonote]
Quick answer might be no, but correct response is yes
C++ does not learn about function hiding, so overriding virtual function without virtual keyword marks that function virtual too.
You aren't creating any copy from the object of e and putting it in d. So d.foo() follows normal polymorphic behavior and calls derived class method. A technique that is declared as virtual within the base class becomes instantly virtual within the derived class also.
The output ("E") reacts just as you might expect it to behave.
The main reason: The dynamic (i.e. runtime) kind of that reference is E. You do a static upcast to D, but that doesn't alter the actual kind of the item obviously.
This is the very idea behind virtual techniques and dynamic dispatches: The thing is the behaviour from the type you had been instantiating, that is E, within this situation.