Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Constructor/virtual destructor with braced initializer list work?

Why doesnt the following code compile?

#include <vector>

class Foo
{
public:
    Foo()
    { }

    virtual ~Foo()
    { }

    std::vector<int> aVec;
};


Foo bar =
{
    { 1, 2, 3, 4, 5 }
};

While following code compiles:

#include <vector>

class Foo
{
public:

    /*Foo()
    { }

    virtual*/ ~Foo()
    { }

    std::vector<int> aVec;
};


Foo bar =
{
    { 1, 2, 3, 4, 5 }
};

Along with the reference to language rules, please elaborate on the rationale behind those rules.

Why does the existence of contructor and virtual destructor stops from initializing?

like image 409
binary_baba Avatar asked Feb 02 '26 03:02

binary_baba


1 Answers

Because Foo is of class type, such that the braced init list is seen as an aggregate initialization. This requires, among others, that the class does not have explicit constructors or virtual members:

Aggregate initialization is a form of list-initialization, which initializes aggregates. An aggregate is one of the following types:

class type (typically, struct or union), that has...

  • no private or protected non-static data members

  • no user-provided, inherited, or explicit (since C++17) constructors (explicitly defaulted or deleted constructors are allowed)

  • no virtual, private, or protected base classes
  • no virtual member functions
  • default member initializers
like image 90
Stephan Lechner Avatar answered Feb 03 '26 17:02

Stephan Lechner