'C++ Polymorphic behaviour with global array of Base Class type
Why is the code below able to demonstrate polymorphic behaviour
TwoDShapes* s2d[2];
int main()
{
Circle c1(/*parameter*/);
Rectangle s1(/*parameter*/);
s2d[0] = &c1;
s2d[1] = &s1;
for (int i = 0; i < 2; i++)
cout << s2d[i]->toString() << endl;
return 0;
}
BUT the code below throws an error
void test();
TwoDShapes* s2d[2];
int main()
{
test();
for (int i = 0; i < 2; i++)
cout << s2d[i]->toString() << endl;
return 0;
}
void test()
{
Circle c1(/*parameter*/);
Rectangle s1(/*parameter*/);
s2d[0] = &c1;
s2d[1] = &s1;
}
I noticed that when I try to initialise the contents of the array within another function other than main(), the Base class'(TwoDShapes) toString() method gets invoked instead of the Derived classes'(Circle and Rectangle) toString() method. But when I do the same thing within main(), it is able to display polymorphic behaviour.
Below is my Base and Derived classes
// Base Class
class TwoDShapes
{
public:
TwoDShapes();
virtual string toString();
string TwoDShapes::toString()
{
return "Inside Base Class toString method";
}
// Derived classes
class Circle : public TwoDShapes
{
public:
Circle(/*parameter*/);
string toString() override;
};
string Circle::toString()
{
return "Inside Circle toString method";
}
*Edit 1: Included a more complete code
Solution 1:[1]
The problem is in your test function, where you create two local objects (c1 and s1) and save their addresses. However, when that function returns, those two objects' lifetimes will end, and the s2d[0] and s2d[1] values will be dangling pointers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Adrian Mole |
