initializer list for derived class

Discussion in 'C++' started by Ralf Goertz, Aug 18, 2011.

  1. Ralf Goertz

    Ralf Goertz Guest

    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?
    Ralf Goertz, Aug 18, 2011
    #1
    1. Advertising

  2. On 08/18/2011 10:53 AM, Ralf Goertz wrote:
    > 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<IntMap::value_type> &lst):IntMap(lst) {}

    > };
    >
    > 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;
    }

    --
    pozdrawiam serdecznie / best regards,
    Bartek 'BaSz' Szurgot

    http://www.baszerr.org
    bartek szurgot, Aug 18, 2011
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Aman
    Replies:
    4
    Views:
    433
    Agent Mulder
    Sep 15, 2003
  2. Replies:
    1
    Views:
    394
    myork
    May 23, 2007
  3. Replies:
    1
    Views:
    385
    Victor Bazarov
    May 23, 2007
  4. chucky
    Replies:
    14
    Views:
    1,284
    Twisted
    Aug 2, 2007
  5. David
    Replies:
    3
    Views:
    401
    Grizlyk
    Jan 29, 2008
Loading...

Share This Page