This is a simplified version of my problem, I want to modify the variable(2d vector in my original code) in base class using function from 2 child classes, while keeping the modified variable and displaying it.
Basically I want to modify the variable declared in base class, by calling functions with the same name from different child classes, and the modified variable will be shared with all child classes. Sorry for my bad understanding of polymorphism, still trying to digest through.
PS:I removed the constructor and virtual destructor from below because stackoverflow won't let me through otherwise.
#include <iostream>
using namespace std;
class Shape
{
protected:
int test[3];
public:
virtual void chgValue() {}
void setInitialValue();
void showValue();
};
void Shape::setInitialValue() //sets test to {1,2,3}
{
test[0]=1;
test[1]=2;
test[2]=3;
}
void Shape::showValue() //display elements of test
{
for(int i=0;i<3;i++)
cout<<test[i]<<" ";
}
class Square : public Shape //child class 1
{
public:
void chgValue()
{
test[1]=5;
}
};
class Triangle : public Shape //child class 2
{
public:
void chgValue()
{
test[2]=7;
}
};
int main()
{
Shape a;
Square b;
Triangle c;
Shape *Shape1=&b;
Shape *Shape2=&c;
a.setInitialValue(); //sets test to {1,2,3}
Shape1->chgValue(); //change test[1] to 5
Shape2->chgValue(); //change test[2] to 7
a.showValue(); //shows 1 2 3 instead of 1 5 7
return 0;
}
Expected output is 1 5 7, but the actual output is 1 2 3.