Without the virtual method, the make_unique line in main compiles ok. But I’m lost as to how to direct-initialize a Derived like this when it’s there. Is this possible?
struct Base
{
virtual void method();
};
struct Derived : public Base
{
int i;
};
int main() {
Base base{}; // this works
make_unique<Derived>(Base{}, 3); // this doesn't compile unless the virtual method is removed
}
I don’t see any mention of virtual methods in the "Direct initilization" page: https://en.cppreference.com/w/cpp/language/direct_initialization
>Solution :
With the virtual method, your Derived class is not an aggregate anymore, so this form of initialization can’t be done.
From cppreference:
An aggregate is one of the following types:
- array type
- class type (typically,
structorunion), that has- no user-declared constructors
(until C++11) - no user-provided, inherited, or explicit constructors
(since C++11)
(until C++20) - no user-declared or inherited constructors
(since C++20) - no private or protected [direct (since C++17)] non-static data members
- no base classes
(until C++17) - no virtual base classes (since C++17)
- no private or protected direct base classes
(since C++17) - no virtual member functions
- no default member initializers
(since C++11)
(until C++14)
- no user-declared constructors