Search code examples
c++oopconstructoroverloadingoperator-keyword

why i m getting [Error] no matching function for call to 'car::car()'


I have created two objects of class car with two member variables a and b....i want to make a new object whose a and b are the product of a and b of the objects that I created earlier.

#include<iostream>
using namespace std;
class car
{
    private:
        int a,b;
    public:
        car(int x,int y)
        {
            a=x;
            b=y;
        }
        void showdata()
        {
            cout<<a<<" "<<b<<endl;
        }
        car add(car c)   // to multiply 'a' and 'b' of both objects and assigning to a new 
                            object 
        {
            car temp;    // new object of class car
            temp.a = a*c.a;   
            temp.b = b*c.b;
            return temp;
        }
        
};
int main()
{
    car o1(3,5);
    car o2(0,7);
    car o3;
    o3=o1.add(o2);
    o1.showdata();
    o2.showdata();
    o3.showdata();
    
}

Solution

  • Have a look at this documentation. https://en.cppreference.com/w/cpp/language/default_constructor

    From this it follows that a default constructor is not added to your class automatically if you define another constructor. Which you did. You will have to add a default constructor manually. eg.

    class car
    {
     public:
         car() = default;
          ....
    
     private:
        int a = 0;
        int b = 0;
    }