initializer list for derived class

R

Ralf Goertz

Hi,

I'm experimenting with the new initializer list feature and I am
wondering why the following doesn't work:


#include <map>

typedef std::map<int,int> IntMap;

struct foo : public IntMap
{
foo(const IntMap &n):IntMap(n) {}
};

int main()
{
IntMap im={{42,0x815}};
foo works=im;
foo doesnt_work={{42,0x815}};
return 0;
}

When trying to initialize "doesnt_work" the compiler (g++ 4.5.1)
complains

error: could not convert ‘{{42, 2069}}’ to ‘foo’

What makes it impossible for foo to be initialized with a list?
 
B

bartek szurgot

Hi,

I'm experimenting with the new initializer list feature and I am
wondering why the following doesn't work:


#include <map>

typedef std::map<int,int> IntMap;

struct foo : public IntMap
{
foo(const IntMap &n):IntMap(n) {}

// either this:
foo(const std::initializer_list said:
};

int main()
{
IntMap im={{42,0x815}};
foo works=im;
foo doesnt_work={{42,0x815}};

// or this:
foo doesnt_work{ {{42,0x815}} };
return 0;
}

When trying to initialize "doesnt_work" the compiler (g++ 4.5.1)
complains

error: could not convert ‘{{42, 2069}}’ to ‘foo’

What makes it impossible for foo to be initialized with a list?

when using '=' to create object you must give a type that can be
directly passed to the c-tor. take a look a simple case:

struct A // your init list
{
};

struct B // your IntMap
{
B(const A &) // notice: c-tor is not explicit
{
}
};

struct C: public B // your foo
{
C(const B&b):
B(b)
{
}
};

int main(void)
{
B b1{ A{} }; // ok
C c1( A{} ); // ok
//C c2=A{}; // oops
C c3=B{A{}}; // ok
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top