Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize static variable on inherited class?

I am trying to create a "parent" class wich provides a common constructor and paramter types to all it's inherited classes. The only thing that changes between the inherited ones is the value of some static variables.

What is the best approach to accomplish this? This is my current attempt:

class Ball {
  public:
    virtual ~Ball();
    Ball ();

  protected:
    static string file;
    static int size;
    node shape;
};

class TenisBall: public Ball {};
class OtherBall: public Ball {};

Ball::Ball () {
  shape = // do something with file and size
};

Ball::~Ball () {
  delete shape;
};

string TenisBall::file = "SomeFile";
int TenisBall::size = 20;

string OtherBall::file = "OtherFile";
int OtherBall::size = 16;

My problem is: I cannot set the static values on the TenisBall and OtherBall class, the compiler only accepts if I change TenisBall and OtherBall for Ball in the last two lines of code. How can I accomplish this? Is this the best approach?

EDIT:

Following the answers provided, I decided to try to implement it using virtual functions. Here is my code so far:

class Ball {
  public:
    Ball () {
      shape = // do something with getSize and getFile
    };

    ~Ball () {
      delete shape;
    };

  protected:
    virtual string getFile(){ return "Fake"; };
    virtual int getSize(){ return 10; };

    node shape;
};

class TenisBall: public Ball {
  int getSize() { return 16; };
  string getFile() { return "TennisBall.jpg"; };
};

int main() {
  TenisBall ball;
  return 1;
};

But, while my editor (xCode) does not gives any error, when trying to compile, llvm gives the following error:

invalid character '_' in Bundle Identifier at column 22. This string must be a uniform type identifier (UTI) that contains only alphanumeric (A-Z,a-z,0-9), hyphen (-), and period (.) characters.

like image 646
Jajajayja Avatar asked Oct 24 '25 15:10

Jajajayja


1 Answers

What you try is not possible. Once a static variable is declared in a class, there is only one variable for this class and even derived classes cannot change this (so you can't change Ball::file to do something different for TennisBall whatever that could mean).

The easiest workaround would probably be changing Ball::file to a virtual function (returning a string or string& to something that could even be class- or function- static) that you can override in a derived class.

like image 51
jpalecek Avatar answered Oct 27 '25 03:10

jpalecek