Consider the code below (note: after rightful criticism I reworded the question):
#include <vector>
using std::vector;
class DataSuper {
public:
DataSuper() {}
};
class DataSub : public DataSuper {
public:
int a;
DataSub() {}
};
class Super {
public:
DataSuper data;
Super() {}
};
class Sub : public Super {
public:
Sub(DataSub i) {
data = i;
}
void test() {
// I would like to print the value of data.a
}
};
int main(int argc, char *argv[]) {
DataSub dataSub;
Super* s = new Sub(dataSub);
s->test();
delete(s);
return 0;
}
Super has an instance of DataSuper called data. Sub, a subclass of Super, has the same object data, but it is an instance of DataSub, which inherits from DataSuper.
In essence, I would like to access data.a from class Sub. I know I can do it with having data as a pointer and then use dynamic_cast, but not sure if this is good practice.
Is there a way I can avoid it WITHOUT having data as a pointer?