IceRise
IceRise

Reputation: 19

error C2512: no appropriate default constructor available: declaration of a object with arguments! inside a constructor

I have a problem with constructors. I have two classes (MyClass1, MyClass2).

MyClass1.h

class MyClass1 {
public:
    MyClass1();
    ...
private:
    MyClass2 object;
    ...
}

MyClass1.cpp

#include "MyClass1.h"

MyClass1::MyClass1() {      //This constructor causes the error!!!
    object = MyClass2(1000);
    ...
}

...

MyClass2.h

class MyClass2 {
public:
    MyClass2(int);
    ...
private:
    int id;
    ...
}

MyClass2.cpp

#include "MyClass2.h"

MyClass2::MyClass2(int id) {
    this->id = id;
    ...
}
...

When creating an instance of 'MyClass1' i get this error message:

error C2512: 'MyClass2': no appropriate default constructor available 

Upvotes: 0

Views: 1146

Answers (2)

songyuanyao
songyuanyao

Reputation: 172864

You're trying to assign object inside the constructor's body, before that object need to be default-constructed, but MyClass2 doesn't have the default constructor.

You should use member initializer list to specify which constructor should be used to initialize object.

Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is finished. Member initializer list is the place where non-default initialization of these objects can be specified.

e.g.

MyClass1::MyClass1() : object(1000) {
}

Upvotes: 3

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36391

The error is that when entering the body of the constructor every member should have been constructed and initialized. As tehre is no ctor with no paramater available for MyClass2 compiler complains.

Syntax to initialize a member object is:

MyClass1::MyClass1() : object(1000) {}

Upvotes: 0

Related Questions