How to convert from base class to derived class?
c++, c++11, class, data-binding, polymorphism
Solution
You can only use polymorphism by using pointers or references, not direct values.
hence, you should use:
QueryInformation::User * user = static_cast<QueryInformation::User *>(&Temp);
and modify your code accordingly to use the pointer instead of the direct value.
Furthermore, the way you allocated `Temp`, it is indeed of class `Base`, not of class `User`, hence its "type" will not be `QueryType_FindUser`, and then `static_cast` will not be perform (you will not enter the `case` value).
The normal use of polymorphism with `static_cast` should look like this:
QueryInformation::Base * temp = new QueryInformation::User;
// or obtain by some other methods, so that you don't know the exact
// type, but anyway you *must* use a pointer (or reference).
switch(temp->type)
{
case QueryInformation::Type::QueryType_FindUser:
{
QueryInformation::User * user = static_cast<QueryInformation::User*>(temp);
}
}
In your case, this means instead of having:
concurrency::concurrent_queue<QueryInformation::Base> BackgroundQueryQueue;
you should have (note the pointer):
concurrency::concurrent_queue<QueryInformation::Base *> BackgroundQueryQueue;
And as Mats suggested, it is probably even better to call a virtual method of `Base` that will do the dispatch automatically, instead of creating yourself a `switch` and making manually a `static_cast`.
Problem
I want to make a multi-threaded model in which the server main loop will not be stalled by pending database transactions. So I made a few simple classes, this is a very simplified version: ``` enum Type { QueryType_FindUser = 1 << 0, QueryType_RegisterUser = 1 << 1, QueryType_UpdateUser = 1 << 2, //lots lots and lots of more types }; class Base { public: Type type; }; class User: public Base { public: std::string username; User(std::string username) :username(username) {type = QueryType_FindUser;} }; ``` Now when I transfer the data as a `Base`, I want to convert it back to `User` class again: ``` concurrency::concurrent_queue<QueryInformation::Base> BackgroundQueryQueue; void BackgroundQueryWorker::Worker() { while(ServerRunning) { QueryInformation::Base Temp; if(BackgroundQueryQueue.try_pop(Temp)) { switch(Temp.type) { case QueryInformation::Type::QueryType_FindUser: { QueryInformation::User ToFind(static_cast<QueryInformation::User>(Temp));//error here //do sql query with user information break; } //etc } } boost::this_thread::sleep(boost::posix_time::milliseconds(SleepTime)); } } ``` Where I marked the `//errorhere` line it says that there is no user-defined conversion from `Base` to `User`, what should I do? How can I define this conversion? I'm new to polymorphism so an additional explaination why this doesn't compile would be also great :) From what I understood about polymorphism it should be doable to convert freely between base<->derived..