I'd like to call the class Foo which has the abstract class Base in its ctor. I'd like to be able to call Foo from Derived which is derived from Base and use Derived's overriding methods rather than Base's.
I'm only able to do this by using a raw pointer as indicated. Is there any way to do this without raw pointers? I tried std::shared_ptr but the compiler complains about abstract classes. Or perhaps is there a better way?
#include <iostream>
class Base {
public:
Base() {
std::cout << "Hello from Base." << std::endl;
}
virtual void show() const = 0;
};
class Foo {
public:
explicit Foo(const Base *s) { // can I avoid this raw pointer?
std::cout << "Hello from Foo." << std::endl;
s->show();
}
Base *s;
};
class Derived : public Base {
public:
Derived() : Base() {
std::cout << "Hello from Derived." << std::endl;
Foo(this);
}
void show() const override {
std::cout << "Hi, I'm Derived::show()." << std::endl;
}
};
int main() {
Derived();
return EXIT_SUCCESS;
}
which produces the following output:
Hello from Base.
Hello from Derived.
Hello from Foo.
Hi, I'm Derived::show().