I'm learning polymorphism in C++ and I can't downcast a pointer to a pointer. I have a class Base and a class Derived that extends Base. And I want to do a pool of Derived objects using a function Base **derivedFactory(size_t size)
. I tried doing Base** array = new Derived*[size];
but the compiler says that it can't convert from Derived** to Base**. So I tried the next:
Base **derivedFactory(size_t size)
{
Base* array = new Derived[size];
for (size_t idx = 0; idx < size; ++idx)
{
Derived derived = Derived();
array[idx] = derived;
}
Base** arrayBase = &array;
return arrayBase;
}
And it compiles. But then when I want to access all Derived objects the main.cc throws a Segmentation fault (core dumped)
. It executes hello(cout) but then it throws before ending the first iteration of the loop.
Could you please help me?
Main.cc
#include "main.ih"
int main()
{
Base **bp = derivedFactory(10);
for (size_t idx = 0; idx <= 10; ++idx)
{
bp[idx]->hello(cout);
cout << "Not printing\n";
}
}
Class Base:
class Base
{
private:
virtual void vHello(std::ostream &out)
{
out << "Hello from Base\n";
}
public:
void hello(std::ostream &out)
{
vHello(out);
}
};
Class Derived:
class Derived : public Base
{
std::string d_text;
private:
void vHello(std::ostream &out) override
{
out << d_text << '\n';
}
public:
Derived()
{
d_text = "hello from Derived";
}
virtual ~Derived()
{}
};
Thank you!