본문 바로가기
번역/Bjarne Stroustrup's C++ Style and Technique FAQ

Why don't we have virtual constructors?

by 겜게준 2019. 2. 26.

왜 가상 생성자는 없는건가요?


가상 호출은 부분적인 정보가 주어지면 작업을 완료하는 메커니즘입니다. 특히 "virtual"은 정확한 타입이 아닌 인터페이스만 알고 있는 상태에서 함수를 호출하게 해줍니다. object를 만들기 위해서는 완성된 정보가 필요합니다. 특히, 생성을 원하는 정확한 타입을 알아야 합니다. 따라서, "call to a constructor"는 virtual이 될 수 없습니다. 객체 생성을 요청할 때 간접 참조를 사용하는 기술은 종종 "Virtual Constructors"로 언급되었습니다. 예를 들면, TC++PL3 15.6.2.을 참고하세요


해당 예제는 추상 클래스를 사용해서 적당한 타입의 오브젝트를 생성하는 기술입니다.


struct F { // interface to object creation functions

virtual A* make_an_A() const = 0;

virtual B* make_a_B() const = 0;

};


void user(const F& fac)

{

A* p = fac.make_an_A(); // make an A of the appropriate type

B* q = fac.make_a_B(); // make a B of the appropriate type

// ...

}


struct FX : F {

A* make_an_A() const { return new AX(); } // AX is derived from A

B* make_a_B() const { return new BX(); } // BX is derived from B

};


struct FY : F {

A* make_an_A() const { return new AY(); } // AY is derived from A

B* make_a_B() const { return new BY(); } // BY is derived from B

};


int main()

{

FX x;

FY y;

user(x); // this user makes AXs and BXs

user(y); // this user makes AYs and BYs


user(FX()); // this user makes AXs and BXs

user(FY()); // this user makes AYs and BYs

// ...

}


이것은 "팩토리 패턴"이라고 불리는 패턴을 변형한 것입니다. 여기서의 포인트는 user()가 AX와 AY같은 클래스들의 존재에 대해 완전히 분리된 것입니다.

댓글