i want this to be working...
I've lots of classes with similar interface. The following class is a placeholder of other classes:
Code:
class Derived : public Base {
static int x;
public:
Derived() {x = 10;}
static int get_x() {return x;}
};
int Derived::x = 0;
Note that get_x() is needed to be a static function for all of the classes. Now I need to access a Derived* through a Base*:
Code:
int main()
{
Base *b = new Derived;
cout << b->get_x() << endl;
delete b;
return 0;
}
My problem is I'm failing to design such a Base class that will allow the above code in main(). b->get_x() should execute the proper derived class's get_x() it is pointing to. Since get_x() must be a static function, I cannot use a virtual method for my Base class. I tried the following versions:
Code:
class Base {
public:
virtual int get_x() {return -1;}
};
which returns -1 always and
Code:
class Base {
public:
virtual int get_x() = 0;
};
with error in Visual C++ 2005: error C2259: 'Derived' : cannot instantiate abstract class.
Can you help me to design a Base class to allow the code in main()? Thanks for reading this.
Re: i want this to be working...
You're getting that error because you didn't define get_x in Derived.
As for your problem, why do you need to have a static virtual function (even though it's evidently not possible)? What is the problem behind it?
Re: i want this to be working...
Well I didn't know that it is impossible to code static virtual function. I did that for lots of similar classes because I wanted the behaviour out of the classes without having to initialize them. Now I need to change this pattern.
Re: i want this to be working...
static methods are not associated with objects; they are associated with classes
virtual method calls look up what method to call at runtime based on the real class of an object; hence they are inherently associated with objects
so these things are in completely different domains
Re: i want this to be working...
It would be interesting to know what situation called for this... Perhaps if you show us we can suggest a better alternative.
Re: i want this to be working...
Actually, this is what I wanted - making static virtual functions. I changed now all of the static class methods to non static, and write abstract base class for them.