c++virtual-functionsclass-members

Can Virtual Classes in C++ have Member Variables?


Suppose I have a purely virtual class, can I do something like this in C++:

class ITreatable
{
    public:
       bool hasBeenTreated;           // <- Can this be here?
       virtual bool Treat() = 0;
};

And if not, how can I ensure that classes which inherit ITreatable have a member variable called hasBeenTreated? Is that possible? Is there some kind of best practice that avoid having to do this / advises against it?

Thanks

Edit: Also how would I define a constructor for such a class?

Edit2: I understand that public member variables are bad practice, I'm just wondering if the design in general is a good idea in C++ or not.


Solution

  • Absolutely.

    Strictly speaking, there is no such thing as a "virtual class". I understand that you are using the term to mean a class constructed of only data members and virtual member functions.

    Consider that only functions can be virtual; if you wish for data members to be accessed polymorphically, you must do this through functions. Thus, use virtual getter/setter functions, and keep your data members private.