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

Hello, I am new at programming in the code below I wanted to put a class into another but an error shows(C++)

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




}

>Solution :

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

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.

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