I’m really confused, so I have to ask this. I try to write an application, but I don’t know how to reach the variables of the derived class, which are in a vector in the Base class.
The code is:
class A {
public:
A() { };
std::vector<A> aVector;
void Foo();
}
class B : public A {
public:
B() { };
int j;
}
void A::Foo() {
aVector.push_back( B() );
// Here I would like to reach B::j, but only the members and variables of A comes in
aVector[0].j; // wrong
B b = aVector[0]; // no suitable user-defined conversion from "A" to "B" exists
// should I use cast? which one?
}
I’m currently learning inheritance and this kind of things through application programming, and now I’m really stuck.
I looked for other questions, but could not find any that solves my problem. If there is, and I missed, then sorry.
You need to store
pointerstoAso that your newBobject won’t get “sliced” (see explanation here) when pushed into the vector.Also, when you want to use specifically a child method / variable on a pointer from the base class, you need to
castit into the proper typeCasting an object like this can be dangerous if you are not 100% sure that it is of the type you’re casting it in.
See this thread for more information on casting (
C style,dynamic_castandstatic_cast)