24

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

0

2 Answers 2

32

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that this behavior is not the case within the base constructor and destructor. There it will call the base implementation. Discussion: cplusplus.com/forum/general/109477
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.