Reputation: 149
class Base
{
private:
Base() = default;
static Base *b;
public:
static Base* get();
};
class Derived: public Base
{
};
Base* Base::b=nullptr;
Base* Base::get(){Base* b = new Derived();return b;}
void main()
{
Base* b = Base::get();
}
I get a compile time error:
main.cpp: In static member function 'static Base* Base::get()':
main.cpp:14:41: error: use of deleted function 'Derived::Derived()'
14 | Base* Base::get(){Base* b = new Derived();return b;}
| ^
main.cpp:9:7: note: 'Derived::Derived()' is implicitly deleted because the default definition would be ill-formed:
9 | class Derived: public Base
| ^~~~~~~
main.cpp:9:7: error: 'constexpr Base::Base()' is private within this context
main.cpp:4:5: note: declared private here
4 | Base() = default;
| ^~~~
In Base::get function, if i do Base* b = new Base(); or remove the private Base() constructor and make it public, i dont get any error.
Upvotes: 1
Views: 265
Reputation: 126203
By making the Base() constructor private, the Derived() default constructor becomes ill-formed (it tries to call the private Base()), so is implicitly deleted. You then try to use it to construct a Derived, which gives you the error you see.
In order to make this work, there needs to be a Derived() constructor -- either one you define yourself, OR arrange for the default one to not be ill-formed. You can do the latter by making Base() public or protected instead of private (so the Derived() constructor can call it).
All the stuff with the static members and virtual functions is irrelevant.
Upvotes: 1