Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using inheritance with static function

I want to design a parent class

//Parent.h
class Parent {
private:
   int currentId;
   static int getIdSquare(); //Just random function for simplicity
}
//Parent.cpp
#include "Parent.h"
int Parent::getIdSquare() { return this->currentId * this->currentId };

Of course this won't work! because you cannot access non-static variable in static function but hold on. I want my child class to be like this

//Child.h
#include "Parent.h"
class Child : public Parent {
private:
    static int index;
};
//Child.cpp
#include "Child.h"
int Child::index = 5;

So that in main when I call Child::getIdSquare(); I will get 25. And I should not be able to call Parent::getIdSquare() because its private. How do I go on about creating something like. This is a non-working code just to illustrate the concept. So if I make another child class i can specified the index in its own body. I want to call the method statically.

Please help me figure out this puzzle!

like image 608
Zanko Avatar asked Jan 17 '26 13:01

Zanko


1 Answers

It sounds like what you are after is really a virtual static function. Unfortunately, that doesn't exist in C++.

Also, Child::getIdSquare() will also be private, and inaccessible in main().

If you need to statically pass a value from a child class to its parent, you may need to do it during the inheritance itself via a template argument.

template <int id>
class Parent
{
public:
    static int getIdSquare() { return id * id; }
}

class Child : public Parent<5>
{
}

Then Child::getIdSquare() will return 25, as required. It doesn't get around the fact that you want Parent::getIdSquare to be private, while making it public in Child though. For that you would need to declare it as private in Parent and then declare it again as public in Child, with an implementation of return Parent<5>::getIdSquare();

Still not ideal, but it's a relatively vague question, so hard to really find a perfect solution here...

like image 143
Mitch Avatar answered Jan 20 '26 05:01

Mitch