Is it possible to disable fields initialization in constructor? I don’t want constructor of my class to call constructors of fields of this class, how can I do it without using malloc? I’d like to do it to avoid double initialization in code like that:
class A() {
A(int n): N(n) {}
}
class B() : public A() {
B(int n) : A(n) {}
B() {
new(this) B(42);
}
}
Simply put: you can’t. Constuctors of members are called always. And it’s good, because an object isn’t constructed if viable parts of it are missing. With viable I mean opposed to optional. Optional in C++ should be expressed by either pointers or
boost::optionalas suggested in the comments.Furthermore it’s a language crime if you call placement new on this inside a constructor, because you initialize an object a second time. Simply said, you are messing with object lifetimes here what is dubious, error prone and hard to understand and maintain at best.
What you are looking for is simply not possible in C++03. What is possible in C++11, however, are so-called delegating constructors, which maybe are what you are looking for:
However, you can’t do everything with them – you can just call another constructor of the same class.