5
votes

C++ has virtual functions, where invoking one will at runtime look up the function address in a vtable.

C++ also has virtual bases. Accessing a data member of a virtual base will at runtime look up the offset the vtable.

Why does C++ lack virtual data members? Accessing one would look up the offset in the vtable as for a virtual base, but the data member would be provided by a derived

virtual void fun();
virtual int val;

void fun() override;
int val override;
1
How would you override a virtual data member without wasting the storage space of the previous data member? - alter igel
It would be wasted, unless declared pure virtual. - Filipp

1 Answers

1
votes

Your talk of offsets is an implementation detail.

The content of a virtual function can change in derived instances.

The content of a non-virtual data member can change in derived instances.

A shared data member in the diamond inheritance sense can be implemented via virtual inheritance.

A polymorphic member can be implemented with a virtual accessor.

At best this is syntactic sugar, and not very much of it.