Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Is "Virtual" inherited to all descendants

Assume the following simple case (notice the location of virtual)

class A {
    virtual void func();
};

class B : public A {
    void func();
};

class C : public B {
    void func();
};

Would the following call call B::func() or C::func()?

B* ptr_b = new C();
ptr_b->func();
like image 691
Jonathan Livni Avatar asked Apr 10 '11 08:04

Jonathan Livni


People also ask

Are virtual methods inherited?

Base classes can't inherit what the child has (such as a new function or variable). Virtual functions are simply functions that can be overridden by the child class if the that child class changes the implementation of the virtual function so that the base virtual function isn't called. A is the base class for B,C,D.

How is virtual inheritance defined?

Virtual inheritance is a C++ technique that ensures only one copy of a base class's member variables are inherited by grandchild derived classes.

How are virtual functions related to inheritance in C++?

A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer.

Can multiple inheritance have virtual function?

Virtual inheritance is used when we are dealing with multiple inheritance but want to prevent multiple instances of same class appearing in inheritance hierarchy. From above example we can see that “A” is inherited two times in D means an object of class “D” will contain two attributes of “a” (D::C::a and D::B::a).


1 Answers

  1. Your code is invalid C++. What are the parentheses in class definition?
  2. It depends on the dynamic type of the object that is pointed to by pointer_to_b_type.
  3. If I understand what you really want to ask, then 'Yes'. This calls C::func:

    C c;
    B* p = &c;
    p->func();
    
like image 140
Yakov Galka Avatar answered Oct 23 '22 18:10

Yakov Galka