I have been working on a little project for a while now and it was going pretty good until I ran into a little bit of a problem. Consider this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <iostream>
#include <memory>
#include <vector>
class Base
{
protected:
virtual void print(int x, int y) const = 0;
};
class DerivedAbstract : public Base
{
protected:
virtual void dummy() = 0;
void addChild(std::shared_ptr<Base> ptr) { children.push_back(ptr); }
std::vector<std::shared_ptr<DerivedAbstract>> children;
};
class Derived2 : public DerivedAbstract
{
protected:
void dummy() override {}
void print(int x, int y) const override {
for(auto it = children.begin(); it != children.end(); ++it)
it->get()->print(503, 747);
}
};
|
This is of course not the code I'm working with but this is to show you the problem.
I have a base class that contains a pure virtual method that has to be implemented in every class that derives from it (to be able to print it). I have the first derived class that implements even more pure virtual methods (dummy()) and a vector of pointers to itself, which is kind of like a "children" vector.
The most important thing about these is the vector. I want to be able to call the overriden method "print()" on every element in the vector. Sadly though, it is not possible as the function is not accessible. How to explain to the compiler that I want to call the
overriden print() method, not the base one like it is assuming.
There will also be more classes that derive from "DerivedAbstract", like "Derived3", "Derived4"... that will be put into the vector.
The print method has to stay protected (I don't want to be able to call it from anywhere in the code, plus I can't change it since it belongs to some external library class).