Here is a little challenge.
I have a base class X
(nonvirtual) and a child class Y
that adds some dependency-specific implementation.
I also have a pure-virtual base A
that defines an interface in terms of X
, and class B
that adds some dependency-specific implementation and relies on Y
features.
class X {
public:
//rule of 0 applies
double getSomething() {return something;}
void setSomething(const double s) {something = s;}
private:
double something{0};
};
class Y : public X {
public:
//rule of 0 applies
int getSomethingElse() {return somethingElse;}
void setSomethingElse(const int s) {somethingElse = s;}
};
The fun begins here!
class A {
public:
virtual void foo(std::unique_ptr<X> basePtr) = 0;
virtual ~A() = default;
protected:
A() = default;
}
class B : public A {
public:
void foo(std::unique_ptr<Y> derivedPtr) {
std::cout << "Something " + derivedPtr->getSomething() + " SomethingElse " + derivedPtr->getSomethingElse();
}
}
The error occurs when attempting to std::make_shared<B>()
:
invalid new-expression of abstract class type 'B' {...}
... note: because the following virtual functions are pure within `B`:
class B : public A {
^
... note: virtual void foo(std::unique_ptr<A>) = 0;
^~~
I can think of one solution, that would be to have the B::foo
signature in terms of X
and to cast the argument to a std::unique_ptr<Y>
in its definition, but I'm wondering if something cleaner exists.