At EasyTechJunkie, we're committed to delivering accurate, trustworthy information. Our expert-authored content is rigorously fact-checked and sourced from credible authorities. Discover how we uphold the highest standards in providing you with reliable knowledge.
A virtual class is a class that is allocated only once in memory, such that children of that class use only the one copy of that parent class which is established in memory. A class is a group of objects that share common traits or attributes. Making a class virtual gives object-orientated programming languages the capability of using multiple inheritance when second or more generation parent classes are derived from common ancestral base classes. Depending on the computer programming language referenced, the "virtual" keyword, similar keyword, or syntax and semantics of a class are used to imply that a particular class is to be considered virtual.
Not all object-orientated programming languages allow multiple inheritance, which is when a child class can be derived from multiple parent classes at the same time. In a programming language like C++, a class can inherit all of the member data and member functions from both parent classes at once and have access to both sets of parent data and functions. Other languages which support multiple inheritance include Perl, Python, Tcl, and Eiffel.
A problem occurs in multiple inheritance hierarchies when two or more parents classes used to create a child class are originally derived from only one or the same grandparent class. This is called the diamond problem, the name stemming from how the hierarchy would look in this situation. When a compiler program tries to instantiate a class, such as a grandchild class made from two parent classes with a common grandparent, two copies of the grandparent are made in memory, one for each parent.
Due to the ambiguity caused by multiple copies of the same grandparent in memory, the compiler is unable to ascertain which copy of the grandparent the grandchild should use to access grandparent data or functions. To remedy this situation, in C++ the grandparent is made into a virtual class when declaring the parents. This causes the compiler to only make one copy of the grandparent in memory that both parents share. Once the grandparent has become a virtual class, the compiler has no problem deciding how the grandchild should access the grandparent because there is only one copy of the grandparent.
Great care should be taken when structuring class hierarchies, especially when they will be included in or become the base for much larger hierarchies in the future. The proper utilization of a virtual class gives class hierarchies greater latitude in development; however, they have the potential to cause errors that are difficult to locate. The study of solid computer programming engineering principles will help to ensure that unexpected side effects from improper program organization do not occur.