Question

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.

Was it helpful?

Solution

The problem is that you actually have 2 instances of base, one as a member and one as a base. Either change into der(int i):base(i),b(i) or remove the member.

OTHER TIPS

Keep in mind that you are adding a member of type base to the der class, which also needs to be constructed. That member is being initialized with the constructor that doesn't take arguments. What you probably meant was:

class base
{
private:
    int num;
public:

    base()
    {
        std::cout << "Default Constructor called \n";
    }
    base (int i) : num(i)
    {
        std::cout << "Int constructor called \n";
    }
};

class der : public base
{
private:
    //base b;
public:
    der(int i):base(i)
    {
        std::cout << "Derived constructor called \n";
    }
};

void main()
{
    der d(12);
}

der has two base instances, as explained by Ylisar. As base has default constructor, it will be implicitly called in der constructor.

Also C++ only supports below two forms of main function, there is no void main() in C++

§3.6.1 Main function

An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

int main() { /* ... */ }

and

int main(int argc, char* argv[]) { /* ... */ }

In your der,There are two base class, one is for inheriting, another one is b(the member of der).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top