简体   繁体   中英

How to use an initialization list to call a constructor?

Hello I am rather new to C++ and looking to call the Rectangle constructor from the Square constructor using an initialization list, in order to assign values to sideA and sideB of the square. Any advice will be appreciated.

class Rectangle
{
public:
    Rectangle (int a, int b);

    // ...

public:
    int sideA;
    int sideB;
};

Rectangle::Rectangle (int a, int b) {
    sideA = a;
    sideB = b;

    if (a < 1)
        sideA = 1;
    if (b < 1)
        sideB = 1;
}

class Square: public Rectangle
{
public:
    Square(int); //constructor
    void setSideA(int);
    void setSideB(int);
};

Square::Square (int a) {
    sideA = a;
    sideB = a;
}

void Square::setSideA(int a) {
    sideA = a;
    sideB = a;
    if (a < 1)
        sideA = 1;
        sideB = 1;
}

void Square::setSideB(int b) {
    sideA = b;
    sideB = b;
    if (b < 1)
        sideA = 1;
        sideB = 1;
}

You can call the base class ( Rectangle ) constructor in the initializer list part of the derived class ( Square ) constructor, thus initializing the "base component" of the derived class in the same way as you can initialize data members (as shown in the initializer list for the Rectangle constructor in the below code):

class Rectangle {
private:
    int sideA, sideB;
public:
    Rectangle(int a, int b) : sideA{ std::max(1,a) }, sideB{ std::max(1,b) } {} // Initialize data
    //...
};

class Square : public Rectangle {
public:
    Square(int s) : Rectangle{ s, s } {} // 'Initializer list' calls base class c'tor
    //...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM