devxlogo

How is Virtual Inheritance Implemented?

How is Virtual Inheritance Implemented?

When multiple inheritance is used, it is sometimes necessary to use virtual inheritance. A good example for this is the standard iostream class hierarchy:

 //Note: this is a simplified description of iostream classesclass  ostream: virtual public ios { /*..*/ }class  istream: virtual public ios { /*..*/ }class iostream : public istream, public ostream { /*..*/ } //a single ios inherited

How does C++ ensure that only a single instance of a virtual member exists, regardless of the number of classes derived from it? C++ uses an additional level of indirection to access a virtual class, usually by means of a pointer. In other words, each object in the iostream hierarchy has a pointer to the shared instance of the ios object. The additional level of indirection has a slight performance overhead, but it’s a small price to pay.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist