0
class Q
{

Q(const Q &obj) {} // copy constructor 
Q& operator= (const Q& a){} // equal op overload
}

template <class T>
class B{
   public : T x;
 B<T>(T t) {
      //  x = t; }
    
}
int main()
{
    Q a(2);
    a.init(1,0);
    a.init(2,1);
    B <Q> aa(a); // this line gives error
}

How to initialize template class with copy constructor? B aa(a); // this line gives error I want to solve it but I could not. Error:

no matching function for call to 'Q::Q()'| candidate: Q::Q(const Q&)|

candidate expects 1 argument, 0 provided| candidate: Q::Q(int)|

candidate expects 1 argument, 0 provided|

1 Answers1

1

To solve the mentioned error just add a default constructor inside class Q as shown below

class Q
{
    Q() //default constructor
    {
      //some code here if needed
    }

    //other members as before
};

The default constructor is needed because when your write :

B <Q> aa(a);

then the template paramter T is deduced to be of type Q and since you have

T x;

inside the class template B, it tries to use the default constructor of type T which is nothing but Q in this case , so this is why you need default constructor for Q.

Second note that your copy constructor should have a return statement which it currently do not have.

Jason
  • 36,170
  • 5
  • 26
  • 60
  • yes it solved the problem but which line is calling default constructor? – elections 12 Nov 28 '21 at 08:32
  • @elections12 I have added the reason why we need the default constructor for `Q` in my answer. Check it out. Basically, when you write `B aa(a);` then the template parameter `T` is deduced to be of type `Q` and since you have `T x;` inside the class tempalte `B`, it tries to use the default constructor of type `T` which is nothing but `Q` in this case. So this is why we need the default constructor of `Q`. – Jason Nov 28 '21 at 08:37