Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Template class initialization in main

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)|

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

candidate expects 1 argument, 0 provided|

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading