mercredi 25 février 2015

Initialization during a pointer cast?

If I define a derived class which has initializers, but end up using pointer casts (i.e. static_pointer_cast), how can I get the initializers to be performed without performing dereference and then an object copy?



#include <string>
#include <memory>

class Base {
public:
std::string Name;
};

class Derived : public Base {
public:
std::string Address = "Initialized";
};


int main() {
auto b_ptr = std::make_shared<Base>();
b_ptr->Name = "Fred";

auto d_ptr = std::static_pointer_cast<Derived>(b_ptr);

fprintf( stdout, "Name: [%s] Address: [%s]",
d_ptr->Name.c_str(),
d_ptr->Address.c_str() ); // Address not valid!
}


Link to code: http://ift.tt/1DWvJrz


What is the proper way to handle this?


Aucun commentaire:

Enregistrer un commentaire