0

I have a nested class structure, Class A is parent and Class B is nested under. When I compile the code, the copy constructor of Class A reports that there is no default constructor for the class B.

error: no default constructor exists for class "A::B"

class A{
   -------
   struct B{
     B(var1, var2){}
   };
   B b;
};

A::A(){ b = new B(Var1, Var2) } // default constructor
A::A(a){ } // copy constructor

Any ideas on how to fix this ?

user1801733
  • 147
  • 1
  • 3
  • 11

2 Answers2

3

You need to use a member initializer in both constructors:

A::A() : b(Var1, Var2) {}
A::A(const A& a) : b(Var1, Var2) {}
Fred Larson
  • 60,987
  • 18
  • 112
  • 174
1

You defined a constructor taking two arguments B(var1, var2) as such a default constructor is not automatically provided for you.

So you have a couple of options.

Choice 1

Add a default constructor for b in your struct B definition

struct B{
    ....
    B() {};
}

also your syntax below is wrong it should be:

A::A() : b() {};
A::A( const A& a) : b() {};

Choice 2

You could use the non default constructor of B but you have to come up with values from somewhere

A::A() : B( valA, valB ) {};
A::A( const A& a) : b(valA, valB) {};

Choice 3

You probably don't want that and instead should create a copy constructor for B and do this

A::A( const A& a) : b(a.b) {};
UpAndAdam
  • 4,515
  • 3
  • 28
  • 46
  • `A` does not derive from `B`, but `A` does have a member named `b` that is of type `B`, so the initialization list in the `A` constructor needs to use `b()` instead of `B()`. – Remy Lebeau Apr 04 '14 at 20:53