I'd like for an inherited class B
to overload a member function func()
of its base class, A
. I know that when accessed by an object of B
, then B::func()
will be called and A::func()
will be hidden unless explicitly referenced via A::
or using
.
Suppose now that A
has another method another_func()
, which calls func()
. Assuming all members and inheritance are public
, of course B
will inherit another_func()
.
Now if I call func()
from B::another_func()
, I want B::func()
to be called, but when I try it, A::func()
is called. Is there a way to achieve the behaviour I'm looking for, for the given code structure?
I found this, but it's not quite the same thing.
The answer here is helpful in general, but doesn't really address my question.
In case the wording was confusing, here it is in code form:
Header:
#include <iostream>
class A
{
public:
void func() { std::cout << "Called A::func()" << std::endl; };
void another_func() { func(); };
};
class B: public A
{
public:
void func() { std::cout << "Called B::func()" << std::endl; };
};
Source:
int main(int argc, char** argv)
{
B B_obj;
B_obj.func();
B_obj.another_func(); // I want this to call B::func?
return 0;
}
The output of this code is:
Called B::func()
Called A::func()
The ouput I want is:
Called B::func()
Called B::func()
The obvious answer is to directly do B::func()
instead of B::another_func()
, but my actual situation is more complicated, and it would be very useful for me to be able to do something similar to the above.
Aucun commentaire:
Enregistrer un commentaire