1

I'm playing around with C++11 and I've compiled the below successfully on Mac OS X using c++ -std=c++11 main.cpp.

#include <iostream>
#include <vector>
#include <string>
using namespace std;


class s {
public:
    s(const string& str) : value {str} {}
    string value;
};

class t : public s 
{
public:
    t(const string& str) : s{"t: " + str} {}
};

int main(int argc, const char** argv) {

    vector<s*> ss1
    {
        new s { "hello" },
        new s { "there" }
    };

    vector<s> ss2
    {
        s { "greeting" },
        s { "father" }
    };

    vector<s> ss3
    {
        { "ahoy" },
        { "matey" }
    };

    vector<s> ss4
    {
        { "bonjour" },
        t { "mademouselle" }
    };

    for (auto &s : ss1) {
        cout << "value: " << s->value << std::endl;
    }

    for (auto &s : ss2) {
        cout << "value: " << s.value << std::endl;
    }

    for (auto &s : ss3) {
        cout << "value: " << s.value << std::endl;
    }

    for (auto &s : ss4) {
        cout << "value: " << s.value << std::endl;
    }

};

The output is here:

value: hello
value: there
value: greeting
value: father
value: ahoy
value: matey
value: bonjour
value: t: mademouselle

The thing that I don't understand is that ss4 is simply a vector<s>, and yet I am able to store the derived class t inside of it. How is this possible?

magnus
  • 4,031
  • 7
  • 26
  • 48
  • 1
    I am not sure this is really a duplicate. There are two parts to the question, the first one, the duplicate how a derived type may be assigned to a base type. But there is another, in the title: *Why does C++11 brace initialization work with stack-based class hierarchies?* -- Should the code compile when using the `std::initializer_list` constructor? – David Rodríguez - dribeas May 05 '15 at 21:17

1 Answers1

4

The thing that I don't understand is that ss4 is simply a vector, and yet I am able to store the derived class t inside of it.

You're not. Your passing a t object, which is used to initialize the s object that gets stored in the vector. See object slicing. You're essentially doing this:

s a = t{"mademouselle"};
juanchopanza
  • 223,364
  • 34
  • 402
  • 480