1

When I try to create more than one object, I get an error saying no matching function for call. I don't understand, usually I can create as many objects as I want without a hitch but the moment I add a parameterized constructor in the equation, suddenly I'm not allowed to create more than one object. Why is it so?

Here's the code:

#include <iostream>

using namespace std;

class Point
{
private:
    int x, y;
public:
    Point(int x1, int y1)
    {
        x = x1;
        y = y1;
    }
    int getx()
    {
        return x;
    }

    int gety()
    {
        return y;
    }
};

int main()
{
    Point c2, c3;
    Point c = Point(10, 20);
    cout << c.getx() << " " << c2.gety() << " " << c3.getx() << endl;
    return 0;
}

1 Answer 1

7

You explicitly declared a constructor Point(int x1, int y1), so the compiler-generated default constructor is disabled.

You can add one to the class declaration like this:

Point() : x(0), y(0) {}

Or, in C++11 or later, you can add a default constructor like this (be careful, the int members won't be initialized by this):

Point() = default;
Sign up to request clarification or add additional context in comments.

1 Comment

"be careful, the int members won't be initialized by this" - they will be if you declare them with default values, eg: private: int x = 0; int y = 0; That is another feature added in C++11 to compliment the = default feature. An alternative would be to simply merge the 2 constructors together: Point(int x1 = 0, int y1 = 0) : x(x1), y(y1) { } That will allow a single constructor to act as both a converting constructor and a default constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.