C++: Is "Virtual" inherited to all descendants
Asked Answered
I

3

8

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();
Interlining answered 10/4, 2011 at 8:49 Comment(1)
yes, declaring a method as virtual makes all its descendants virtualCorazoncorban
I
6

Examples using pointers as well as reference.

  • Using pointer

    B *pB = new C();
    pB->func(); //calls C::func()
    
    A *pA = new C();
    pA->func(); //calls C::func()
    
  • Using reference. Note the last call: the most important call.

    C c;
    B & b = c;
    b.func(); //calls C::func() 
    
    //IMPORTANT - using reference!
    A & a = b;
    a.func(); //calls C::func(), not B::func()
    

Online Demo : http://ideone.com/fdpU7

Investigate answered 10/4, 2011 at 9:2 Comment(0)
F
7
  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();
    
Fist answered 10/4, 2011 at 8:54 Comment(3)
@Amir: he IS asking yes/no question.Investigate
@Amir: "Is “Virtual” inherited to all descendants" sounds like a yes/no question to me.Bratwurst
@Amir: really? I've always thought that questions of the form "Is ..." and "Would ..." are yes/no questions.Fist
I
6

Examples using pointers as well as reference.

  • Using pointer

    B *pB = new C();
    pB->func(); //calls C::func()
    
    A *pA = new C();
    pA->func(); //calls C::func()
    
  • Using reference. Note the last call: the most important call.

    C c;
    B & b = c;
    b.func(); //calls C::func() 
    
    //IMPORTANT - using reference!
    A & a = b;
    a.func(); //calls C::func(), not B::func()
    

Online Demo : http://ideone.com/fdpU7

Investigate answered 10/4, 2011 at 9:2 Comment(0)
S
3

It calls the function in the class that you're referring to. It works it's way up if it doesn't exist, however.

Try the following code:

#include <iostream>
using namespace std;

class A {
    public:
    virtual void func() { cout << "Hi from A!" << endl; }
};

class B : public A {
    public:
    void func()  { cout << "Hi from B!" << endl; }
};

class C : public B {
    public:
    void func()  { cout << "Hi from C!" << endl; }
};

int main() {
  B* b_object = new C;
  b_object->func();
  return 0;
}

Hope this helps

Sunflower answered 10/4, 2011 at 8:54 Comment(1)
Apologies for that - I completely missed that in his post. Amended. My answer still stands though ;)Sunflower

© 2022 - 2024 — McMap. All rights reserved.