# Silly Question Regarding Virtual

## Recommended Posts

Raeldor    254
Hi all, Quick and probably silly question regarding virtual. If I have class1 that has a virtual function and I override that function in class2 but do not use the virtual qualifier does that mean that if I have a class3 that inherits from class2 that the class3 function (again overriden) will not be called when that method is executed against the class if it is cast as class1 or class2? Thanks!

##### Share on other sites
Way Walker    745
Quote:
 Original post by RaeldorQuick and probably silly question regarding virtual. If I have class1 that has a virtual function and I override that function in class2 but do not use the virtual qualifier does that mean that if I have a class3 that inherits from class2 that the class3 function (again overriden) will not be called when that method is executed against the class if it is cast as class1 or class2?

Yes, but that has nothing to do with the use of "virtual".
#include <iostream>struct A            { virtual void foo() { std::cout << "class A\n"; } };struct B : public A {         void foo() { std::cout << "class B\n"; } };struct C : public B {         void foo() { std::cout << "class C\n"; } };int main() {    C  c;    A *pa = &c;    B *pb = &c;    static_cast<A>(c).foo();    static_cast<B>(c).foo();    pa->foo();    pb->foo();}

Prints out:
class Aclass Bclass Cclass C
It's the cast.

##### Share on other sites
BTownTKD    205
"virtual" quantifiers are inherited, so if you make the "bottom" class a virtual function, then all classes inherited from it (no matter how far down the heirarchy tree) will be virtual too.