What I know
I know that returning a const reference of a temporary object is ok! (like this example:)
class A {
public:
virtual const A& clone () { return (A()); }
virtual std::string name() const { return ("A"); }
};
Returning temporary object and binding to const reference
But!
If I would want to do that, It is still correct:
class B : public A {
public:
virtual const A& clone () { return (B()); }
virtual std::string name() const { return ("B"); }
};
I would think yes, but in execution time, the returned object is still considered as a A object (like in this example:)
main.cpp
#include <iostream>
#include <string>
int main() {
B bb;
A* aa = &bb;
std::cout << aa->clone().name() << std::endl;
}
output
valgrind ./a.out
==14106== Use of uninitialised value of size 8
==14106== at 0x401BF9: main (main.cpp:8)
==14106== Uninitialised value was created by a stack allocation
==14106== at 0x401BF2: main (main.cpp:8)
B
It's a B.. yay.. but this warning is quite horrifing....
Edit
Thanks to you i know see my error... but i would want to know some other things about it...
When this is executed, what exactly in the stack is happening?