2

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; 
}

Mayuu
  • 39
  • 7

2 Answers2

3

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
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
1

You're creating a local LoginRequest object:

LoginRequest l = LoginRequest();

taking that address:

r = &l;

and returning it:

return r;

but l goes out of scope on the next line:

}

Instead you want to create it on the heap:

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

Also use smart pointers rather than raw pointers.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54