0

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;
}
rossca
  • 1
  • This is what virtual functions are for. You use virtual function to access members of derived class. See your C++ textbook for more information on virtual functions and how to use them. – Sam Varshavchik Jan 23 '21 at 21:05
  • Your `A` is not polymorphic, you cannot know its most derived type reliably. – bipll Jan 23 '21 at 21:06
  • What are _"attributes"_, can you elaborate that in your question please? This term is used in various contexts, but none of these matching your question. – πάντα ῥεῖ Jan 23 '21 at 21:06
  • You can cast your `A*` to a `C*` using `dynamic_cast` or `static_cast`. With that said, the real solution to the problem is to make sure that your base class has whatever virtual methods you need to abstract away the need to know what specific derived type you have. Or if you really need to know, then store the derived types instead of the base class. – super Jan 23 '21 at 21:11

0 Answers0