Hi I am a C++ beginner just encountered a problem I don’t know how to fix
I have two class, this is the header file:
class A
{
public:
int i;
A(int a);
};
class B: public A
{
public:
string str;
B(int a, string b);
};
then I want to create a vector in main which store either class A or class B
vector<A*> vec;
A objectOne(1);
B objectTwo(2, "hi");
vec.push_back(&objectOne);
vec.push_back(&objectTwo);
cout << vec.at(1)->i; //this is fine
cout << vec.at(1)->str; //ERROR here
I am really confused, I checked sites and stuff but I just don’t know how to fix it, please help
thanks in advance
The reason this won’t work is because the objects in your vector are of (static) type
A. In this context, static means compile-time. The compiler has no way to know that anything coming out ofvecwill be of any particular subclass ofA. This isn’t a legal thing to do, so there is no way to make it work as is. You can have a collection ofB, and access thestrmember, or a collection ofAand not.This is in contrast to a language such as Python, where a member will be looked up in an object’s dictionary at runtime. C++ is statically typed, so all of your type-checking has to work out when the code is compiled.