Reputation: 6480
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.
Upvotes: 33
Views: 29820
Reputation: 2291
Acordingly to MSDN an interface has these characteristics:
So I would response to your question with
NO if you want an interface
and
Yes if you just use abstract classes, but as the others say, make them private and use public getters and setters
Upvotes: 9
Reputation: 385405
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.
Upvotes: 36
Reputation: 2235
That is possible. C++ doesn't have interfaces enforced by the language, so your example acts like normal class definition without any special rules.
It's considered bad practice to declare variables as public in classes. You might want to make it private and declare accessor/mutator for it or declare it as protected.
Upvotes: 3
Reputation: 14233
Yes.
There is no concept of a "pure virtual" class in C++, merely abstract classes with virtual members.
As for whether there is a best practice, I would say that the biggest practice that should be followed in this example is not to use public variables. Rather, have a setter/getter defined in the base class that modifies a private variable.
Upvotes: 4