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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With