Search code examples
c++functionpolymorphismdowncast

How can I downcast a pointer after passing it through a function?


I created a function which returns a base pointer to a derived object which is created in the func. It seems like it doesn't work! As if the derived data is lost, and the pointer is pointing to a base object...

There is class Request, which is the base class, and there is class loginRequest - which derives Request. In order to check the type of object, I printed the object's name (typeid(*r).name()). Inside the func(), the printing output turned out to be "loginRequest", which is good because this is the pointed object. (look at the code) BUT after returning this pointer, when I print it's type again, it turns out to be "Request". Can you guys please help me? why does the returned pointer lose the derived data?


Request * r = new Request();
r = func(); // r is now supposed to point the LoginRequest object.
std::cout<< typeid(*r).name() <<std::endl; //print the type of OBJECT

//func
Request * func()
{
    Request * r;
    LoginRequest l = LoginRequest();
    r = &l;
    std::cout<< typeid(*r).name() <<std::endl;  //print the type of OBJECT
    return r; 
}


Solution

  • You're returning a pointer to an object, l, that has automatic storage duration.
    Dereferencing the returned pointer has undefined behaviour.

    You need to create that object dynamically with new, and remove the memory leak that's caused by your misuse of new outside the function:

    Request* func()
    {
        Request* r = new LoginRequest();
        std::cout<< typeid(*r).name() <<std::endl;  //print the type of OBJECT
        return r; 
    }
    
    
    // ...
    
    Request * r = func();
    std::cout << typeid(*r).name() << std::endl; //print the type of OBJECT