[C++] 생성자 위임

  • Post author:
  • Post category:
  • Post comments:0 Comments
  • Post last modified:September 10, 2007

C# 쓰다가 C++ 코딩을 하다 보면 불편한 점이 한두 가지가 아닌데, 그 중 하나가 Chain Constructors 패턴을 적용하기 어렵다는 점이다. C#에선 간단하게 Chain Constructors 패턴을 구현해 코드 중복을 최소로 줄일 수 있다.

초기화 함수
public class MyBaseClass
{
    public MyBaseClass (int x) : base() // Invoke the parameterless constructor in object
    {
        Console.WriteLine ("In the base class constructor taking an int, which is "+x);
    }
}

public class MyDerivedClass : MyBaseClass
{
    public MyDerivedClass () : this (5) // Invoke the MyDerivedClass constructor taking an int
    {
        Console.WriteLine ("In the derived class parameterless constructor.");
    }

    public MyDerivedClass (int y) : base (y+1) // Invoke the MyBaseClass constructor taking an int
    {
        Console.WriteLine ("In the derived class constructor taking an int parameter.");
    }
}
	

하지만 C++로는 이게 어렵다. 기껏해야 초기화 함수를 따로 만들어놓고, 생성자에서 초기화 함수를 불러내는 방식이 가능할 뿐이다. 한데 인터넷을 뒤지다 보니 이 기능이 C++ 표준에 포함되었다고 한다. 2006년 4월에 승인 받은 듯 한데, 언제쯤 벤더가 이를 지원하는 제품을 내놓을지 궁금하다.

초기화 함수
class Message
{
//..
 void init()
 {
  buff=0;
  msg_id=0;
  msg_length=0;
 }
public:
 explicit Message(int n) { init(); }
 explicit Message(const char * ptr) { init(); }
 explicit Message(const A& a) { init(); }
};
	
생성자 위임
class Message
{
 char *buff;
 int msg_id;
 size_t msg_length;
public:
 //target constructor. Invoked by all other ctors
Message() :
  buff(0),msg_id(0),msg_length(0){}//#1

 //the following three ctors invoke the target ctor

explicit Message(int) :
  Message() {} //delegate the initialization to #1
explicit Message(const char *p) :
  Message() { /* additional code*/ }
explicit Message(const A& a) :
  Message() { /*additional code*/ }
};
	
Author Details
Kubernetes, DevSecOps, AWS, 클라우드 보안, 클라우드 비용관리, SaaS 의 활용과 내재화 등 소프트웨어 개발 전반에 도움이 필요하다면 도움을 요청하세요. 지인이라면 가볍게 도와드리겠습니다. 전문적인 도움이 필요하다면 저의 현업에 방해가 되지 않는 선에서 협의가능합니다.
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments