페이지

2013년 6월 22일 토요일

C++ 생성자 함수가 가상함수가 될 수 있을까?

이 글은 c++에서 왜 생성자 가상함수가 허용되지 않는가에 대한 이유를 설명하는 글입니다.
아래 링크의 내용을 참고하였으나 제 마음대로 해석한 내용이므로 원본의 문장과는 다를 수 있습니다.

http://www.stroustrup.com/bs_faq2.html#virtual-ctor


답은 될 수 없다.

왜냐면 virtual 함수의 역할은 정해진 정보를 주기 위한 것이다.
OOP 에서 "virtual"의 기능은 확실한 타입을 모르는 객체의 인터페이스를 알게 해주기 위한 것이다.


하지만 하나의 객체를 생성하기 위해선 완전한 정보가 필요하다. 어떤 타입의 객체를 생성하려고 하는지 말이다. 그렇기 때문에 논리적으로 생성자 함수는 virtual 이 될 수가 없다.

간접적으로 생성자 함수를 virtual 로 호출하는 방법은 물론 있다.

아래의 예를 보자.


 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
  // ...
 }

위 예제는 factory 패턴의 다른 형식이다. 여기서 요점은 user()가 AX 와 AY와 같은 클래스들에 대해 전혀 모른다는 것이다.



댓글 없음:

댓글 쓰기