Consider the following class structure:-
class foo {
public:
int fun () {
cout << "in foo" << endl;
}
};
class bar_class1:public foo {
public:
int fun () {
cout << "in bar_class1" << endl;
}
};
class bar_class2:public foo {
public:
float fun () {
cout << "in bar_class2" << endl;
}
};
main () {
foo * foo_pointer = new bar_class1();
foo_pointer->fun();
}
The output of the above program is in foo. Is there a way, that using a pointer of type foo *
which actually points to an object of type bar_class1
or bar_class2
, we can call the fun
function of the derived class instead of the base class? I am not able to make the fun
function virtual in the base class foo
since, then there is a return type conflict for function foo
in the derived class bar_class2
.