Home > Net >  Hello, I am new at programming in the code below I wanted to put a class into another but an error s
Hello, I am new at programming in the code below I wanted to put a class into another but an error s

Time:04-18

So i created the class Point and want to use it as the parameter of the constructor in the class Circle , but the error : There is no default constructor for class "Point" shows up and I dont know how to fix it. The code is represented below this text:

class Point {
private:
    int x, y;
public:
    Point(int X, int  Y) {
        x = X;
        y = Y;
    }

};


class Circle {
private:
    int radius;
    Point centre;

public:
    Circle(Point q, int r) {
        centre = q;
        radius = r;


    }


};

int main() {
    Point obj = Point(3, 4);
   Circle obj = Circle(obj, 3);




}

CodePudding user response:

The first problem is that when the constructor Circle::Cirlce(Point, int) is implicitly called by the compiler, before executing the body of that ctor, the data members centre and radius are default initialized. But since you've provided a user-defined ctor Point::Point(int, int) for class Point, the compiler will not synthesize the default ctor Point::Point(). Thus, the data member centre cannot be default initialized.

To solve this you can use constructor initializer list as shown below. The constructor initializer list shown below, copy initialize the data member centre instead of default initializing it.

class Point {
private:
    int x, y;
public:
    Point(int X, int  Y) {
        x = X;
        y = Y;
    }

};
class Circle {
private:
    int radius;
    Point centre;

public:
//--------------------------vvvvvvvvvvvvvvvvvvvv--->constructor initializer list used here
    Circle(Point q, int r): radius(r), centre(q)
    {
     
    }
};

int main() {
    Point obj = Point(3, 4);
   Circle circleObj(obj,4);
}

Demo

Additionally, you had 2 objects with the same name obj inside main.

  • Related