-2

I wanted to override an internal call in a base class and keep the same interface and general algorithm. The changes depend on the state of the object and thus can't just be set once in the constructor. Is there a way to get this to work? Or perhaps a design pattern for this?

#include <iostream>
using namespace std;

class X
{
private:
    virtual void internalCall()
    {
        cout << "Class X" << endl;
    }
public:
    X()
    {
        internalCall();
    }
    void externalCall()
    {
        internalCall();
    }
};

class Y : public X
{
protected:
    virtual void internalCall2()
    {
        cout << "Class Y2" << endl;
    }
    virtual void internalCall()
    {
        cout << "Class Y" << endl;
        internalCall2();
    }
    public:
    Y() : X() {}

};

int main()
{
    Y y;

    y.externalCall();

    return 0;
}

Desired output:

Class Y

Class Y2

Class Y

Class Y2

Actual output:

Class X

Class Y

Class Y2

On my machine:

Class X

Class X

eengineer
  • 177
  • 2
  • 9
  • 1
    Post some code that actually compiles and you'll see the expected output. See this example: http://ideone.com/GN4jeh – juanchopanza Sep 25 '14 at 21:34
  • 3
    Please show the actual code you had for this problem, what you've posted works fine: http://ideone.com/0K9LX7 – Red Alert Sep 25 '14 at 21:37
  • Related reading: http://stackoverflow.com/questions/2170688/private-virtual-method-in-c – hyde Sep 25 '14 at 21:45
  • So obviously my code is more complex, but I've reproduced half of it when the internal call is in the constructor. I'm still getting different behavior with the last call too, not sure what is going on. http://ideone.com/EzLRyG – eengineer Sep 25 '14 at 21:55
  • @Envy - What did you expect this to do? `X() {internalCall();}` – PaulMcKenzie Sep 25 '14 at 22:01

1 Answers1

0

The issue is that you are calling internalCall() from the constructor of X. Even though it's a virtual function, at the time the constructor for X is called, Y hasn't been created yet - so you get X's internalCall().

Red Alert
  • 3,786
  • 2
  • 17
  • 24