royK
royK

Reputation: 73

Is it possible to use the base class constructor to initialize values to base class private members using derived class?

What I would like to do is set the width and the height variables of the Shape class using the Rectangle class.

Shape.h

class Shape
{
    public:
        Shape(int x, int y);
    private:
        int width;
        int height;
};

Shape.cpp

Shape::Shape(int x, int y): width(x), height(y)
{
}

Rectangle.h

class Rectangle: public Shape
{
    public:
        Rectangle(int, int);
};

Rectangle.cpp

Rectangle::Rectangle(int x, int y):Shape(x, y)
{
}

Main.cpp

int main()
{
    Rectangle rec(10,7);
    return 0;
}

What I want to do is use the rec object to initialize the width and height variables of the class Shape which are private. Is there any way to do that? Or do I need to set the width and height variables to protected?

Upvotes: 0

Views: 74

Answers (2)

Felix Glas
Felix Glas

Reputation: 15524

Your current implementation of Rectangle correctly calls the base constructor using its parameters. Using modern C++ (at least C++11) the implementation of Rectangle can be simplified by using inheriting constructors:

struct Rectangle : public Shape {
    using Shape::Shape;
};

To access the private member, it needs to either be changed to public, or you need to implement a getter method in the base class. Alternatively you can make the private member protected and implement the getter in the derived class (although, as height is common to all derived classes, it would be appropriate to place the getter in the base class).

class Shape {
/* ... */
public:
    int get_height() const { return height; }
};
std::cout << rec.get_height() << std::endl;

Upvotes: 1

Arash
Arash

Reputation: 2164

Your code already compiles fine except for you cannot have access to rec.height in your main function as it is private.

A derived class inherited publically have access to the public constructor of the based class.

int main()
{
    Rectangle rec(10,7);
    // cout << rec.height << endl;  <----------- disabled
    return 0;
}

Upvotes: 0

Related Questions