jamesatha
jamesatha

Reputation: 7620

Calling an overridden method from the base class

Let's say I have the following classes:

class A {
 public:
  virtual void foo() {
    bar();
  }

 protected:
  virtual void bar() {
    // Do stuff
  }
}

class B : public A {
 protected:
  virtual void bar() {
    // Do other stuff
  }
}

If I have an instance of B and call the foo method, which bar method would get called? And is this compiler specific?

Thanks

Upvotes: 24

Views: 16234

Answers (2)

Kaaf
Kaaf

Reputation: 390

You can't, but you can get around it. In this case you can add a true default bool argument to the A constructor, and pass a false to it in B:

class A 
{
public:
    A(bool construct = true) { 
        if (!construct) return;
        bar(); 
    }
    virtual void bar() { cout << "A::bar" << endl; }
};

class B : public A 
{
public:
    B() : A(false) { bar(); }
    void bar() override { cout << "B::bar" << endl; }
};

int main()
{
    A a;
    B b;
}

Output:

A::bar
B::bar

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

The A::foo will call B::bar if you have an instance of B. It does not matter if the instance is referenced through a pointer or a reference to a base class: regardless of this, B's version is called; this is what makes polymorphic calls possible. The behavior is not compiler-specific: virtual functions behave this way according to the standard.

Upvotes: 32

Related Questions