In the code below the initializer list is initialized with a B and a C object whose ctors pass in values “bbb” and 333 respectively. Since these objects derive from A, the list properly creates two A elements.
#include <string>
#include <vector>
#include <iostream>
struct A
{
char ch;
};
struct B : A
{
B( std::string str ) : str( str ) {}
std::string str;
};
struct C : A
{
C( int num ) : num( num ) {}
int num;
};
struct D
{
D( std::initializer_list< A* > initializerList )
: variadicVect( initializerList )
{}
std::vector< A* > variadicVect;
};
int main()
{
D d { new B { "bbb" }, new C { 333 } };
d.variadicVect[ 0 ]->ch = 'm'; // ok, but accesses base member
//std::cout << d.variadicVect[ 0 ]->str << std::endl; // error C2039: 'str': is not a member of 'A'
//std::cout << d.variadicVect[ 1 ]->num << std::endl; // error C2039: 'num': is not a member of 'A'
return 0;
}
A similar problem was reported in link resolved by @Jarod42. He identified Object Slicing as the problem. To avoid this assignment-by-value issue, I new’d the initializer list object, but am still unable to access the derived class.
Another attempt I tried was to templatize the initializer_list type (code not shown), but I got this error: ‘D::variadicVect': only static data member templates are allowed’
My goal is to be able to initialize the list with various derived objects choosing the derived type at compile time and yet be able to access them properly at runtime. Is that possible?