Search code examples
c++objectdefault-constructor

C++ Initialization of member objects which do not have default constructor:


Similar questions have been answered but I still cannot find a solution to my problem. I am indeed not able to call the constructor of class Point inside class Rectangle. After having read some answers, I would approximately do it like this, but it does not work:

class Point {
public:
  Point(int x, int y);

private:
  int x;
  int y;
};

Point::Point(int xx, int yy) {
  x = xx;
  y = yy;
}

class Rectangle {
public:    
    Rectangle(Point a, Point b) : Point(int x, int y); // this is wrong
 
private:
    Point a;
    Point b;
};

Rectangle::Rectangle(Point aa, Point bb) :  Point(int x, int y) { // same as above
    ?
}

Can anyone help me to understand how to implement and fix this code (I know that declaring Rectangle as a struct makes it way easier)?


Solution

  • It is not clear what you expected this line to do:

    Rectangle(Point a, Point b) : Point(int x, int y);
    

    The place to initialize members is not the constructors body. And the correct syntax for the member initiazer list is:

    Rectangle(Point a, Point b) : a(a), b(b) {}
    

    Note that the initializer list is a place where shadowing is not an issue, you can use the same name for parameter and member, because there is no ambiguity. a(a) initializes the member a with parameter a.


    Note that also constructor of Point should be:

    Point::Point(int xx, int yy) : x(xx),y(yy) {
    }
    

    For int members it won't make a huge difference, but for class types it does make a huge difference: Members are initialzed before the body of the constructor runs. Fist initializing and then assigning in the constructor is inefficient and sometimes just wrong. On the other hand, there is no reason to not use the initializer list when the members are ints.


    PS

    (I know that declaring Rectangle as a struct makes it way easier)?

    I think you refer to members being public in the struct. However, struct and class are just two different keywords to declare a class. The only difference is default access (see here for details: When should you use a class vs a struct in C++?) and those two definitions are identical:

    class foo { 
        int a;
    public:
        int b;
    };
    struct foo {
    private:
        int a;
    public:
        int b;
    };