I am coding in C++11 and I have a large parent non-static function and I want to reuse it in my derived class.
The parent non-static function uses a static function defined in itself. I have overloaded the static function in my derived class and I want the parent non-static function to use the static function of the derived class. But it doesn't and uses its own version. A similar question was asked but this is different in the sense that it deals with static as well as non-static members of a class. For example, see the sample code below:
#include <iostream>
class Base
{
public:
static int value() { return 0; }
int getValue() { return value(); }
};
class Derived:public Base
{
public:
static int value() { return 1; }
};
int main()
{
Derived obj;
std::cout << obj.getValue() << std::endl;
return 0;
}
I want the code the print 1 but it prints 0
Is there any way I can do that? Thanks a lot for helping.
Update #1
For me, the getValue()
function is quite big, which is why I asked the question in the first place. Overriding the getValue()
function in the derived class, as suggested in the comments might be a feasible option but for me, it would be copying a large function multiple time, since I have multiple derived classes, which would make it cumbersome to make changes in the future. Briefly saying,
I want to define a non-static, public function once in a parent class which uses a static member of the class, and then reuse the non-static function in every child class in such a way that in case I overload the static function of the parent class in the child class, the non-static function of the parent class uses the overloaded function.