How can I force a derived class to override a base class member variable?

Hello All,

I'm new to C++ (been an Ada guy for over 20 years), and I've search but can't find an answer to my question on the Web (big place!), so I'm hoping you Gurus come help me.

I know that for virtual functions, if you declare it with an "= 0" (pure virtual) it not only designates the base class as an "abstract class", but also forces the derived class to define an implementation.

Is there a way to do this for variables? What I really want is something like (not 100% on syntax, so please forgive):

class Base
{
public:
virtual void dummyMakeMeAbstract() = 0; // don't allow instantiations

protected:
virtual const static typeXXX mustOverrideVariable;
}


class Derived : public Base
{
public:
void dummyMakeMeAbstract(){};

protected:
const static typeXXX mustOverrideVariable = myValue;
}

I could live without the const static behavior if I had to.

Thanks in advance !!!
Is there a way to do this for variables?


No.

The parent class needs to know the type in order to be able to use it -- and if the type definition is up to the child class, then the parent class can't know the type, and therefore can't use the variable consistently. Remember that Parent must be the same everywhere, even if the child classes differ greatly.

I don't see why you'd need such a construct, though. What would you need this for? Maybe there's a better/alternative way to approach the problem.
Thanks for your reply Disch.

I think I have it solved from a reply on another forum. He suggested just using a pure virtual function to return the value of the variable I was trying to force to be overridden.

The reason for the desired behavior/design is that I have a set of messages which have the some fields (such as MessageId) that are common structurally, but must have unique values for each message type derived from the base class message.
Here's a thought. Not sure if it helps....


1
2
3
4
5
6
7
8
template< typename T >
class Base {
    T variable;
};

class Derived : public Base<int> {
   // etc ...
};


Topic archived. No new replies allowed.