-3

I have a class called A.

It has an instance or B:

public:
    B inst;

B's constructor is like B::B(int, int).

When creating the A class's constructor A::A() { }, it gives me the following error:

No matching function for call to B::B()

when I haven't created or mentioned any B in A's constructor. Any idea?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
XorTroll
  • 51
  • 7

2 Answers2

3

Constructing A requires all of A's data members to be constructed. In this case, B must be default-constructed as you did not provide a member initialization list. As B defines a non-default constructor, generation of its implicit default constructor is suppressed - that's why you're getting the error.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
1

When class A contains an instance of class B, constructing an instance of A also requires construction of the contained instance of B.

If no constructor of B is listed in the initialiser of class A, the default is to invoke a constructor of B that accepts no arguments. For example

 class A
 {
     public:
      A::A() {};

     private:

       B b;
 };

is functionally equivalent to

 class A
 {
     public:
      A::A() : b() {};

     private:

       B b;
 };

This involves a constructor of B with no arguments. If no such constructor exists, the result is a diagnostic (error message). Since you have declared/defined a constructor with arguments, a constructor for B with no arguments is not implicitly generated.

Peter
  • 35,646
  • 4
  • 32
  • 74