Sign in to follow this  
Raeldor

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 this post


Link to post
Share on other sites
Way Walker    745
Quote:
Original post by Raeldor
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?


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 A
class B
class C
class C
It's the cast.

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this