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

Started by
3 comments, last by SirLuthor 18 years, 10 months ago
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
Advertisement
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
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
makingroulette, I think your code with correct that made Anonymous Poster is the most simpliest way to do what you want
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]
Free speech for the living, dead men tell no tales,Your laughing finger will never point again...Omerta!Sing for me now!

This topic is closed to new replies.

Advertisement