Pepe
Pepe

Reputation: 6480

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.

Upvotes: 33

Views: 29820

Answers (4)

thedarkside ofthemoon
thedarkside ofthemoon

Reputation: 2291

Acordingly to MSDN an interface has these characteristics:

  • An interface class (or struct) must be declared within a namespace and may have public or private accessibility. Only public interfaces are emitted to metadata.
  • The members of an interface can include properties, methods, and events.
  • All interface members are implicitly public and virtual.
  • Fields and static members are not permitted.
  • Types that are used as properties, method parameters, or return values can only be Windows Runtime types; this includes the fundamental types and enum class types.

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

Lightness Races in Orbit
Lightness Races in Orbit

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

Nekuromento
Nekuromento

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

riwalk
riwalk

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

Related Questions