0

I have a class (B) that inherits another class (A). I want to call a function from class A that has been overridden. I also want to be able to call the overridden function independent of what class inherited the base (say class C : public A , where I want to call C's version of the function.)

Here's an example

class A {

public:
    void callF();
    virtual void f() {};
};

class B : public A {

public:
    void f();
};

void A::callF()
{
    //FYI, I want to be able to call this without knowing what the super class is.
    f();
}

void B::f()
{
    std::cout << "I want this function to be called, but instead the default f() is called.";
}

Edit: In my real code, I have an std::vector<A> aVector;. Then I would call aVector.push_back(B());. If I called aVector[0].callF();, The default a::f() would be called. As answered below, I have a problem with slicing.

curiousguy
  • 8,038
  • 2
  • 40
  • 58
sFuller
  • 1,305
  • 2
  • 14
  • 23
  • Please clarify your question a bit. You want to be able to call the overridden function f() when it is called from the base-class. In the example above, when you call f() in the class A, you want the overridden function in B to be called. Is that so? – Gangadhar Mar 10 '12 at 02:29
  • That is right. Also, say I implemented `class C` which inherits A. When I call `C c; c.callF()`, I would want it to call C's version of f(). – sFuller Mar 10 '12 at 02:34
  • The code you have given us does exactly what you ask for. If your program is behaving differently, the problem may lie in what you are **not** showing us. Please create a small, *complete* program that demonstrates the problem and paste that program into your question. http://sscce.org/ – Robᵩ Mar 10 '12 at 02:40
  • Where is your virtual inheritance? – curiousguy Jan 14 '17 at 14:14

3 Answers3

1

Your construction:

vector_of_A.push_back( B() );

doesn't store a B in the vector. It constructs a B, then constructs an A from that, then stores that A in the vector. As a consequence, you experience slicing.

See this for more info:

https://stackoverflow.com/a/4403759/8747

Community
  • 1
  • 1
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
1

Your code is correct.

You may be getting the behavior you observed because your were calling f() or callF() from the constructor of A. That's the only case I can think of where A::f() would get invoked instead of B::f().

selbie
  • 100,020
  • 15
  • 103
  • 173
0

Your code works for me with this little test program:

int main()
{
    // Instantiate B, and reference it via a base class pointer.
    A* b = new B;

    b->callF();
    delete b;
}

Output:

I want this function to be called, but instead the default f() is called.

When calling a virtual member function within a base class member function, it's the derived member function that will be invoked.

Emile Cormier
  • 28,391
  • 15
  • 94
  • 122