views:

56

answers:

2

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

A: 

Firstly, post the full error message.

Secondly, if you have an A*, the compiler can't infer that some subclass (B in this case) has a field called str and hence you will get a compiler error.

Alex
+1  A: 

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 of vec will be of any particular subclass of A. This isn't a legal thing to do, so there is no way to make it work as is. You can have a collection of B, and access the str member, or a collection of A and 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.

danben