C++ – Constructor or Initialize Method to Startup [duplicate]

Possible Duplicate:
Avoid having an initialization method

I want to determine when to do non-trivial initialization of a class. I see two times to do initialization: constructor and other method. I want to figure out when to use each.

Choice 1:

Constructor does initialization

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>MyClass::MyClass(Data const& data) : m_data()
{
// does non-trivial initialization here
}
MyClass::~MyClass()
{
// cleans up here
}
</code>
<code>MyClass::MyClass(Data const& data) : m_data() { // does non-trivial initialization here } MyClass::~MyClass() { // cleans up here } </code>
MyClass::MyClass(Data const& data) : m_data()
{
    // does non-trivial initialization here
}

MyClass::~MyClass()
{
   // cleans up here
}

Choice 2:

Defer initialization to an initialize method

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>MyClass::MyClass() : m_data()
{}
MyClass::Initialize(Data const& data)
{
// does non-trivial initialization here
}
MyClass::~MyClass()
{
// cleans up here
}
</code>
<code>MyClass::MyClass() : m_data() {} MyClass::Initialize(Data const& data) { // does non-trivial initialization here } MyClass::~MyClass() { // cleans up here } </code>
MyClass::MyClass() : m_data()
{}

MyClass::Initialize(Data const& data)
{
    // does non-trivial initialization here
}

MyClass::~MyClass()
{
    // cleans up here
}

So to try and remove any subjectivity I want to figure out which is better in a couple of situations:

  1. Class that encapsulates a resource (window/font/some sort of handle)
  2. Class that composites resources to do something (a control/domain object)
  3. Data structure classes (tree/list/etc.)
  4. [Anything else you can think of]

Things to analyze:

  1. Performance
  2. Ease of use by other developers
  3. How error-prone/opportunities for bugs
  4. [Anything else you can think of]

4

Always use the constructor unless there is a good reason not to. It’s “The C++ Way” ™.

Regarding your points to consider:

  1. Constructors are always more or equally efficient as having code outside in separate init() functions.

  2. Constructors tend to be easier to use for other developers. Without looking at your source or docs, I would expect new YourClass(stuff) to work. Having to call a yourClass->init(stuff) afterwards is not enforced by the compiler and it’s an easy slip up to make.

  3. As per number 2 – a lot of caveats about constructors are fleshed out by compilers for you, in terms of order of initialization etc. When you move things out of constructors you face the danger of reinventing the wheel, sometimes as a square.

4

Ideally, just use a constructor. It is usually a bad thing when a constructor returns a not-quite-usable object.

However, as people have pointed out, you often have situations where the data needed to fully initialize an object is not available at construction time. You can deal with a situation like that by using the Builder Pattern.

Let’s say you have a class Foo, which requires some non-trivial initialization. You create a class FooBuilder, which simply stores all the data needed to initialize an object of Foo. FooBuilder would have a member function (aka method) Foo *build() or maybe Foo build(), which you would call when all the data is collected. It might also have setters for various items that need to be passed to Foo’s constructor, and it might supply defaults for some of those.

This solves the problem of “late initialization” without requiring an initialize() member function. For example, if you need to create an array of Foo objects before you have all the stuff to initialize them, you would instead create an array of FooBuilders. Then you would call the appropriate setters on the builders as data becomes available. Finally, when all the data are safely stored in the builders, you create an array of Foo‘s, by calling build() on each builder.

One option that no one seemed to touch on is instead of constructing then Init, using a private constructor and a static Initialize function. Indeed this is a powerful technique because in theory the static initialize function might construct different subclasses based on context.

I would choose one or the other. As others have mentioned, having a constructor followed by an Initialize call is error prone.

3

Use an Init() when you have to supply parameters to your object that you don’t/can’t know when you create the object.

You could also use it if your class’s functionality could take along time to construct, e.g. initialising the playback of a video file involves file parsing, video codec matching and loading, audio codec matching and loading, resource acquisition. In this case you might to break up the creation into asynchronous steps so your user’s app remains responsive and also allows then to cancel the operation.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật