• Advertisement
Sign in to follow this  

Silly Question Regarding Virtual

This topic is 4362 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
"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
Sign in to follow this  

  • Advertisement