I am hoping someone can give me the technical details of why the following will not compile, and if possible, a work around.
I have an existing struct called Foo, and code which uses initializer lists to create instances of Foo. This code compiles and works:
struct Foo {
int id1;
int id2;
};
int main()
{
Foo f({1,2});
return f.id1;
}
I would like Foo to implement an interface going forward:
struct Interface {
// All pure virtual methods, but this won't compile even if empty
};
struct Foo : public Interface{
int id1;
int id2;
};
int main()
{
Foo f({1,2});
return f.id1;
}
This code no longer compiles, with errors in the vein of
cannot convert argument 1 from 'initializer list' to 'const _Ty &'
(Error changes depending on your exact compiler.)
I have found this section of the standard relating to aggregate initialization:
[dcl.init.aggr]/1 An aggregate is an array or a class (Clause 12) with 1.1 no user-provided, explicit, or inherited constructors (15.1), 1.2 no private or protected non-static data members (Clause 14), 1.3 no virtual functions (13.3), and 1.4 no virtual, private, or protected base classes (13.1).
Though I am not actually sure if aggregate initialization is what's occurring here. Can someone explain the error that's occurring, and if possible, offer changes I could make to the interface? I have several existing structs which need this interface, and lots of existing code which uses this form of initialization, and I'd like to rewrite as little of it as possible. Thank you!
struct Interface {}; struct Foo : public Interface { int id1; int id2; }; int main() { Foo f = { .id1 = 1, .id2 = 2 }; return f.id1; }
and claim it's for C++20? :-) ` – Bobbiebobbin