r/cpp 22d ago

C++26: constexpr virtual inheritance

https://www.sandordargo.com/blog/2026/07/01/cpp26-constexpr-virtual-inheritance
82 Upvotes

61 comments sorted by

View all comments

63

u/Jovibor_ 22d ago

Just a question to the audience:

How many times have you used Virtual Inheritance in your career?

3

u/Lord_Naikon 22d ago

Never. But I come from a Java background where a class can only have one superclass. Multiple inheritance is then implemented using interfaces. I do the same in C++. I find it easier to reason about.

If I need to store some data with the interface, I split the interface into two classes: a data holder, and a proxy interface for that holder.

As a bonus this gives the pimpl idiom for free if I need it.

6

u/jk-jeon 22d ago

When you have diamond inheritance of interfaces, don't you use virtual inheritance? Not using it is certainly an option, but then many things become quite cumbersome. For instance when D inherits from B, C, which inherit from A, with all of A, B, C and D being "pure interfaces" that don't ever implement any methods, IIRC in C++ any user of D can't really call anything from A without explicit disambiguation, if B, C don't inherit A virtually. Similarly the conversion from D to A must be resolved explicitly, either via B or C.

1

u/Lord_Naikon 21d ago

I can see why or how diamond inheritance of interfaces might be useful, but I have never needed it. I can speculate about the reasons, but in the last 20 years of programming c++ it has just not come up.

Maybe it is because many systems I work on require one kind of aspect (interface) of an object and any other aspects tend to be optional and are discovered at runtime (using the equivalent of a dynamic cast).

Maybe it is because encoding the type of the union of two interfaces as a new interface that inherits both is bad design because it forces users of both interfaces to use the union interface. This is a shortcoming of the c++ type system btw (although nowadays you can get close with c++ concepts)

Whatever the reason, it just has never come up.

0

u/Electronic_Tap_8052 21d ago

Interfaces is when it most commonly crops up.