Jonathan Livni
Jonathan Livni

Reputation: 107102

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();

Upvotes: 8

Views: 771

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361482

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

Upvotes: 6

Ben Stott
Ben Stott

Reputation: 2218

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

Upvotes: 3

Yakov Galka
Yakov Galka

Reputation: 72489

  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();
    

Upvotes: 7

Related Questions