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.
Abstract classes (apart from pure virtual functions) can have member variables, non-virtual functions, regular virtual functions, static functions, etc.
There are several kinds of variables: Member variables in a class—these are called fields. Variables in a method or block of code—these are called local variables. Variables in method declarations—these are called parameters.
As to why C++ doesn't have virtual variables: Virtual functions permit polymorphism; in other words, they let a classes of two different types be treated the same by calling code, with any differences in the internal behavior of those two classes being encapsulated within the virtual functions.
@andre: Just an idea: Virtual data members could be used for mixins or duck typing. When 2 classes A and B both define a virtual int count , then a derived class which inherits A and B could carry only a single (as it is virtual) count member.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With