Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Virtual Classes in C++ have Member Variables?

Tags:

c++

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.

like image 456
Pepe Avatar asked May 18 '11 23:05

Pepe


People also ask

Can virtual class have member variables?

Abstract classes (apart from pure virtual functions) can have member variables, non-virtual functions, regular virtual functions, static functions, etc.

Can classes have member variables?

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.

Can member variables be virtual C++?

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.

Can data member be virtual?

@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.


1 Answers

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.

like image 152
Lightness Races in Orbit Avatar answered Sep 24 '22 06:09

Lightness Races in Orbit