가상 상속(Virtual inheritance)은 기본 클래스 멤버 변수의 복사본 하나만 손자 파생 클래스에서 상속되도록 보장하는 C 기술이다. 가상 상속이 없으면 두 클래스 B와 C가 클래스 A에서 상속되고 클래스 D가 B와 C 모두에서 상속되는 경우 D에는 A 멤버 변수의 두 복사본(하나는 B를 통해, 다른 하나는 C를 통해)이 포함된다. 범위 확인을 사용하여 독립적으로 액세스할 수 있다.

대신, 클래스 B와 C가 클래스 A로부터 가상으로 상속된다면 클래스 D의 객체는 클래스 A의 멤버 변수 세트 하나만 포함하게 된다.

이 기능은 가상 기본을 파생 클래스와 이 클래스에서 파생된 모든 클래스에 대한 공통 하위 개체로 만들기 때문에 다중 상속에 가장 유용하다. 이는 파생 클래스(위 예의 D)의 관점에서 가상 기본 클래스(A)가 마치 직접 기본 클래스인 것처럼 작동하므로 사용할 조상 클래스에 대한 모호성을 명확하게 하여 다이아몬드 문제를 방지하는 데 사용할 수 있다. D는 기본(B 또는 C)을 통해 간접적으로 파생된 클래스가 아니다.[1][2]

상속이 부분의 구성보다는 집합의 제한을 나타낼 때 사용된다. C에서는 계층 전체에서 공통으로 사용되는 기본 클래스를 virtual 키워드를 사용하여 virtual로 표시한다.

다음 클래스 계층 구조를 고려할 것.

UML virtual inheritance.svg

struct Animal {
    virtual ~Animal() = default;    // Explicitly show that the default class destructor will be made.
    virtual void Eat() {}
};

struct Mammal: Animal {
    virtual void Breathe() {}
};

struct WingedAnimal: Animal {
    virtual void Flap() {}
};

// A bat is a winged mammal
struct Bat: Mammal, WingedAnimal {};

각주 편집

  1. Milea, Andrei. “Solving the Diamond Problem with Virtual Inheritance”. 《Cprogramming.com》. 2010년 3월 8일에 확인함. One of the problems that arises due to multiple inheritance is the diamond problem. A classical illustration of this is given by Bjarne Stroustrup (the creator of C++) in the following example: 
  2. McArdell, Ralph (2004년 2월 14일). “C++/What is virtual inheritance?”. 《All Experts》. 2010년 1월 10일에 원본 문서에서 보존된 문서. 2010년 3월 8일에 확인함. This is something you find may be required if you are using multiple inheritance. In that case it is possible for a class to be derived from other classes which have the same base class. In such cases, without virtual inheritance, your objects will contain more than one subobject of the base type the base classes share. Whether this is what is the required effect depends on the circumstances. If it is not then you can use virtual inheritance by specifying virtual base classes for those base types for which a whole object should only contain one such base class subobject.