Hi all.I am a beginner in C++ and have following question regarding polymorphism.I want that getPolygon will act as Rectangle.But within the method getPolygon width and height is correct but outside of that method not.What is not correct in my example below?
Polygon * getPolygon() {
Polygon * result = & Rectangle(2, 3); // rectangle is destructed here
result->toString(); // accessing nonexisting object
return result;
}
// is almost the same as
Polygon * getPolygon() {
Rectangle fubar(2, 3)
Polygon * result = & fubar;
result->toString();
return result;
// fubar is destructed here
}
In both versions above the getPolygon returns a memory address. That address has no valid object after the end of the function call. In your version it did not have one already when you did call the toString.
In Polygon * result = & Rectangle(2, 3); you do create an unnamed temporary Rectangle object, whose lifetime does not extend beyond this one statement.
You should use dynamically allocated memory, if you want the object to outlive a function. Then you have to manage the memory too (read: deallocate appropriately). You should look up std::unique_ptr and std::shared_ptr, for they help in the management.
Another note. Constructors are convenient:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class Polygon {
public:
Rectangle() = default;
Rectangle( int width, int height )
: width(width), height(height)
{
}
void set_values(int a, int b);
// code
};
class Rectangle : public Polygon {
public:
Rectangle(int width, int height)
: Polygon(width, height)
{
}