Sign in to follow this  
makingroulette

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

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
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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this