Copy constructor calling the default constructor during delegation instead of the appropriate one

75 Views Asked by At

So I have the following Box class:

Box.h

#ifndef BOX_H
#define BOX_H

class Box {

    private:
        double _length {1.0},
                _width {1.0},
                _height {1.0};

        // can be modified in const member functions
        mutable unsigned count {};

    public:
        Box() = default;
        Box(double length, double width, double height);
        Box(double side);

        Box(const Box& box);

        double volume() const;

        friend double surfaceArea(const Box& aBox);

        double& length() { return _length; }
        double& width() { return _width; }
        double& height() { return _height; }


        double length() const { return _length; }
        double width() const { return _width; }
        double height() const { return _height; }



};

#endif

Box.cpp

#include "Box.h"
#include <iostream>

Box::Box(double length, double width, double height) : _length {length}, _width {width}, _height {height} {}
Box::Box(double side) : Box {side, side, side} {}
Box::Box(const Box& box) : Box {box.length, box.width, box.height} {}

// Function to calculate the volume of a box
double Box::volume() const {
    return this -> _length * this -> _width * this -> _height;
}

main.cpp

#include <iostream>
#include <memory>
#include "Box.h"

int main() {

    Box box1 {2.0, 3.0, 4.0};
    Box box2;
    auto box3 { std::make_unique<Box>(15.0, 20.0, 25.0) };

    std::cout << "Volume of box1 = " << box1.volume() << std::endl;
    std::cout << "Surface area of box1 = " << surfaceArea(box1) << std::endl;

    std::cout << "Volume of box2 = " << box2.volume() << std::endl;
    std::cout << "Surface area of box2 = " << surfaceArea(box2) << std::endl;

    std::cout << "Volume of box3 = " << box3->volume() << std::endl;
    std::cout << "Surface area of box3 = " << surfaceArea(*box3) << std::endl;

}

double surfaceArea(const Box& aBox) {
    return 2.0 * (aBox._length * aBox._width + aBox._length * aBox._height + aBox._height * aBox._width);
}

enter image description here

Based on these error messages I'm concluding that there is an issue with the delegating constructor of the copy constructor. So i'm not sure why it seems like the code is calling the default constructor instead of the 3-arg constructor.

1

There are 1 best solutions below

0
David G On

You have to add a pair of parenthesis if you want to call the functions:

Box::Box(const Box& box) : Box {box.length(), box.width(), box.height()} {}