user13575381
user13575381

Reputation:

Default constructor is being called with no reference to it

why the following code won't work:

#include <iostream>

class Entity
{
public:
    /*
    Entity()
    {
        std::cout << "Create Entity with default constructor" << std::endl;
    }
     */

    Entity(int x)
    {
        std::cout << "Create Entity with " << x << std::endl;
    }
};

class Example
{
    Entity ent;
    int age;

public:
    Example()
            //: ent(7), age(7)
    {
        ent=Entity(7);
        age=7;
    }
};

int main() {
    Example s1;
    return 0;
}

it says that it need default constructor for Entity but why is that? the only Entity object I'm using is built using the constructor that uses 1 argument.

Plus, why changing Example s1; to Example s1(); will cause my code to work in different way (I can't see any printings on the screen.

Upvotes: 0

Views: 276

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

Within the body of this constructor

Example()
        //: ent(7), age(7)
{
    ent=Entity(7);
    age=7;
}

the data member ent that is used in the assignment statement (in assignment operators can be used already constructed objects)

    ent=Entity(7);

must be already constructed. However it can not be constructed using the default constructor that is absent. This expression Entity( 7 ) does not create the object ent. It creates a temporary object that is assigned to ent by using the default copy assignment operator implicitly defined by the compiler.

You have to write at least

Example() : ent(7), age(7)
{
}

specifying explicitly the called constructor with parameter in the mem-initializer list of the constructor of the class Example. In this case the data member ent will be created using this constructor before the control will be passed to the body of the constructor of the class Example.

Upvotes: 1

R Sahu
R Sahu

Reputation: 206717

When you explicitly define any constructor, the implicitly defined default constructor is deleted and is not available for use.

When you don't initialize a member explicitly using initialization list syntax in a constructor, the default constructor is used to initilize it.

Example()
{
    ent=Entity(7);
    age=7;
}

is equivalent to

Example() : ent(), age()
{
    ent=Entity(7);
    age=7;
}

That explains the compiler error. To fix the error, use

Example() : ent(7), age(7)
{
}

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409404

Inside the Example constructor, the member variable ent already needs to be constructed. It's this construction that is meant by the error.

The solution is to use a constructor initializer list, which you have commented out in the example shown.


As for

Example s1();

That declares s1 as a function that takes no arguments and returns an Example object by value.

Upvotes: 2

Related Questions