I have a class A, with derived classes B & C.
Using a vector, defined as storing pointers to objects of class A, I'm storing pointers to some objects of class B, and some objects of class C.
When I address a pointer to an object, from the vector, how can I access class B or C specific attributes?
Currently, as the vector is defined as storing pointers to objects of class A, I can only access base class attributes.
Example:
#include <iostream>
#include <vector>
using namespace std;
class A {
public:
int ID;
A(int ID)
: ID(ID) {}
};
class B: public A{
public:
int price;
B(int ID, int price)
: A(ID), price(price) {}
};
class C: public A{
public:
int weight;
C(int ID, int weight)
: A(ID), weight(weight) {}
};
int main() {
B * objB = new B(1, 1);
C * objC = new C(1, 100);
vector<A *> objVector;
objVector.push_back(objB);
objVector.push_back(objC);
//How do I access weight here?
int accessedWeight = objVector[1]->weight;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire