In the first your case class A has no virtual function. So its non-virtual function displayStuff will be called. in the second case when you added function specifier virtual to the function in class A the corresponding function inclass B redefines this function. So in the second case the function of class B is called because the table of virtual function pointers contains a pointer to the function defined in class B.
virtual function in inhertiance hierarchy
-
24-09-2022 - |
Frage
When I have something like this, and when I have a* mya=new c();
and I call a->displayStuff
it calls Class a
method, and when virtual
is in Class a
instead of Class b
, it calls Class b
method.
Since Class c
has no implementation of this method, what is the rule applied here?
class a
{
public:
void displayStuff() {}
//other methods
};
class b:public a
{
public:
virtual void displayStuff() {}
//other methods
};
class c:public b
{
//other methods
};
Lösung
Andere Tipps
Since Class c has no implementation of this method, what is the rule applied here?
The rule of inheritance applies. Based on the visibility of the inherited member and the inheritance type, the members visible in Class B would be visible in Class C. In this case, as you are inheriting publicly, all public members would be visible publicly. So, the public virtual member function in Class B would be visible as a public virtual function in Class C.
Exactly, but when to use what and why when I have multiple levels of inheritance?
Its a design decision. Remember, a non virtual member function is bound at compile time, so any Function Call via a base pointer cannot be resolved until you intend to call the function. Consider the scenario
Base
public: foo
/ \
/ \
/ \
/ \
/ \
Derived1 Derived2
public: foo public: foo
Base *p;
std::cin>>cond;
if (cond)
p = new Derived1();
else
p = new Derived1();
p->foo();
In the above code, the decision to call foo() (Derived1::foo or Derived2::foo), depends on some external condition which cannot be determined at runtime. The only way to make this possible is create a vTable which can only be forced to be created if we make at-least one function in a class virtual (Note any virtual function in the base class continues to remain virtual in the derived class).