Given a base class Shape
and a derived class Rectangle
, I want to access the member variable size
of Rectangle by the following code:
class Shape
{
public:
Shape() {};
};
class Rectangle
{
public:
Rectangle(int width) {width=width;}
int width;
};
//execute this code during runtime
std::shared_ptr<Shape> ptr = std::make_shared<Rectangle>();
ptr->width; // is this possible ???
I am having a more complicated code, where this results in an error. Conversely, if compute_area()
were an overwritten member function of Rectangle
, ptr->compute_area()
would give no error.
First, your code contains a big problem. Rectangle does not inherit from Shape, so std::shared_ptr<Shape> ptr = std::make_shared<Rectangle>();
will throw an error. You need to class Rectangle : public Shape
to fix it
As for access to the member variable width via ptr, you will need to cast Shape to Rectangle. You can do it a few ways, which will depend on what you're code is doing. If you are 100% sure ptr can cast to Rectangle, you can do this:
std::shared_ptr<Shape> ptr = std::make_shared<Rectangle>();
auto rect = std::static_pointer_cast<Rectangle>(ptr);
rect->width; // you can now access it
However, you should always evaluate your need to do this in the first place. Casting like this is usually a really big code smell that indicates a flaw in your design or approach to the problem. There are times when it is appropriate to make cast like this, but without seeing the rest of your code there is no way to make that assessment here. I suggest you avoid casting, look into why you need to do it with your current design, and redesign around not needing the cast. This sounds easier than it is, especially if you are new to it, but it is well worth doing for writing maintainable code.