Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to direct-initialize a derived class with an abstract base?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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, struct or union), 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading