If I have a vector of pointers to a superclass and add members of a subclass to the vector, I can call a subclass function just fine, but as my code is right now, I can't access variables that are unique to the subclass. How do I access B
from a pointer in vec
?
#include <iostream>
#include <vector>
class Super {
public:
int A;
Super(int a) : A(a) {}
virtual void foo() = 0;
};
class Sub : public Super {
public:
int B;
Sub(int a, int b) : Super(a), B(b) {}
void foo() {
std::cout << "calling foo from Sub\n";
}
};
int main() {
std::vector<Super*> vec;
vec.push_back(new Sub(2, 3));
vec[0]->foo(); // No problem
std::cout << "A: " << vec[0]->A << std::endl; // No problem
std::cout << "B: " << vec[0]->B << std::endl; // Compile Error
}