• Advertisement
Sign in to follow this  

is there a better way to do this? virtual static variables

This topic is 4644 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

These classes do what i want, But im sure its not the best way as I am very inexperienced in C++. The method RetrieveNumber() will be shared by many classes including CA that derive from C, but the value this function returns needs to come from static variables that are defined in derived classes(CA). What im looking for is virtual static variables, as a work around ive used the function GetNumber() to achieve the effect of a virtual static variable. Does anyone know of a better way of doing this that is more elegant class C { public: virtual int GetNumber() const = 0; int RetrieveNumber() { return GetNumber(); } }; class CA : public C { public: virtual int GetNumber() const { return 10; } }; Your help is much appreciated

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
just a thought:
isn't it better to use just a virtual Retrievenumber
i don't think there is a cleaner, better way of doing this

Share this post


Link to post
Share on other sites
I might be misunderstandin your question but can't u do something like:

class C
{
private:
static int number;
public:

static int RetrieveNumber() { return number; }
};


class CA : public C
{
public:

};

I think this may work, just add a similar method to set the number if needed

Share this post


Link to post
Share on other sites
makingroulette, I think your code with correct that made Anonymous Poster is the most simpliest way to do what you want

Share this post


Link to post
Share on other sites
Here's what I would do.. Firstly, there is no such thing as a virtual static variable as far as I know. What you can do instead is have a virtual function return a private variable value. And make sure it is private, not protected, that way, it will not get inherited. Thus, you have something like this:

class C
{
public:
C() { C::myVal = 0; }
~C();

virtual int Variable() { return C::myVal }
protected:
private:
static int myVal;
};

class CA
{
public:
C() { CA::myVal = 1; }
~C();

virtual int Variable() { return CA::myVal }
protected:
private:
static int myVal;
};



Now, I can't promise you that this solution will work 'out of the box', because I haven't checked it for syntax errors or anything like that, but the concept should be the solution you're looking for.

[EDIT] Whoops, forgot I was working in notepad, and didn't indent.. Sorry 'bout that.. [grin]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement