I was reading effective C++ and I couldn’t really understand one of the mentioned benefit of initialization list.From what I understand is that initialization lists also help to avoid calling of unnecessary default constructors especially when they are not needed. So in order to test that I created a simple code example as such
class base
{
public:
base()
{
std::cout << "Default Constructor called \n";
}
base (int i)
{
std::cout << "Int constructor called \n";
}
};
class der : public base
{
private:
base b;
public:
der(int i):b(i)
{
std::cout << "Derived constructor called \n";
}
};
void main()
{
der d(12);
}
No where I assumed that only the int constructor will be called instead both the constructors of the base class are called. Could anyone please clarify this concept.
The problem is that you actually have 2 instances of
base, one as a member and one as a base. Either change intoder(int i):base(i),b(i)or remove the member.