mardi 5 mai 2015

Why does C++11 brace initialization work with stack-based class hierarchies? [duplicate]

This question already has an answer here:

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?

Aucun commentaire:

Enregistrer un commentaire