-1

When I write a constructor of a class which has an other class' object, like in the example below, I get the compiling error error: no matching function for call to 'A::A()'

class A {
    int x;
public:
    A(int _x) {
        this->x=_x; } };

class B {
    A obj;
public:
    B(int x) {
        obj=A(x); } };

int main(){}

I know that by adding a constructor of A with no parameters (like A(){}) i would solve the problem, but there is another way to solve it without introducing a new constructor?

p.s.: i know using a pointer to A insted of a object of class A, would solve, but I want to know if there's a way keeping the object.

matteo_c
  • 1,990
  • 2
  • 10
  • 20

1 Answers1

1

Use member initializer list.

For members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.

class B {
    A obj;
public:
    B(int x) : obj(x) {}
};

For your code, obj will be default initialized at first then assigned in the constructor's body. A can't be default initialized; which causes the error.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405