I've been struggling with with this C++ thing for a while. I've created base object class and derived object class and I'm trying to store references to both base and derived objects in a vector of base-class pointers (avoid object slicing). With pointer, I am able to run virtual methods and I can confirm that pointer points to derived-class object, however I cannot get to derived class specific variables. Is there any way of doing it ?
Base class object:
class Base
{
public:
Manager* manager;
Base(){}
Base(Manager* mManager){
manager = mManager;
}
virtual void init(){}
virtual void speak() {
std::cout << "Base class is speaking!" << std::endl;
}
};
Derived class object:
class Derived : public Base
{
public:
Manager* manager;
int DerviedVariable = 100;
Derived(){}
Derived(Manager* mManager){
manager = mManager;
}
void speak() override {
std::cout << "Derived class is speaking!" << std::endl;
}
};
Those objects (Base na Derived) are created and stored using Manager class and array called groupedEntities :
constexpr std::size_t maxGroups = 32;
using Group = std::size_t;
class Manager
{
public:
std::array<std::vector<Base*>, maxGroups> groupedEntities;
void addToGroup(Base* mBase, Group mGroup)
{
groupedEntities[mGroup].emplace_back(mBase);
}
std::vector<Base*>& getGroup(Group mGroup)
{
return groupedEntities[mGroup];
}
template <typename T, typename... TArgs>
T* addEnt(TArgs&&... mArgs)
{
T* e(new T(this));
return e;
}
};
I am create objects and try to reference them like that :
void main() {
std:size_t groupBlob = 0u;
Manager* manager = new Manager();
Derived* blob1(manager->addEnt<Derived>());
Derived* blob2(manager->addEnt<Derived>());
manager->addToGroup(blob1, groupBlob);
manager->addToGroup(blob2, groupBlob);
auto& grouped(manager->getGroup(groupBlob));
for (auto& e : grouped)
{
e->speak();
std::cout << e.DerviedVariable ;
}
}
Unfortunately, e.DerviedVariable is inaccessible, whereas speak() function says "Dervied class is speaking". Is there any way to access Derived-class variables with this architecture? Thanks
main()must be declared to returnint. - Ted Lyngmovirtual int getDerviedVariable() = 0;toBaseand implement it inDerived- Richard Critten