Inheritance; calling polymorphic function

I have the following situation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

using namespace std;

class Base
{
    public:
        Base()      {cout<<"Base::Base()"       <<endl;}
        Base(int v) {cout<<"Base::Base(int v)"  <<endl;}
        void foo()  {cout<<"Base::foo()"        <<endl;}
};

class Derived: public Base
{
    public:
        Derived()               {cout<<"Derived::Derived()"         <<endl;}
        Derived(int v) :Base(v) {cout<<"Derived::Derived(int v)"    <<endl;}
        void foo()              {cout<<"Derived::foo()"             <<endl;}
};

int main()
{
    Base* pThing = new Derived();

    pThing->foo();

    return 0;
}


which outputs:


Base::Base()
Derived::Derived()
Base::foo()


What I really want to happen is that the Derived::foo() is invoked in place of the Base::foo()

The only thing I have the liberty of changing is my Derived class. This is an issue I am having with a project in a class of mine and the instructor created the main function and the Base class. My job was to develop the Derived class. I would like to state again, I can not change the Base class or the Main function.

Another thing I would like to state is that I believe my teacher to be an idiot, and as such, it is very possible that what I am trying to do here is impossible. If it is just let me know and I will go talk to him.

Thank you for your time,
Brandon
Last edited on
Cast the pointer. (change main)
To use polymorphic functions, those need to be defined virtual in the base class. (change base class).

No, there is no way if you just want to touch Derived
Last edited on
+1 ne555

The right thing to do here would be to make 'foo' virtual in Base.

But since you cannot change base, the problem is unsolvable.
Topic archived. No new replies allowed.