Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++ not have virtual data members?

Tags:

c++

virtual

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;
like image 999
Filipp Avatar asked Nov 07 '22 02:11

Filipp


1 Answers

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.

like image 123
Yakk - Adam Nevraumont Avatar answered Nov 14 '22 22:11

Yakk - Adam Nevraumont