Here is the code which causes a problem:
class Base
{
public:
virtual void fun()
{
cout<<"Base";
}
};
class Der:public Base
{
Base &pb;
public:
Der(Base&b):pb(b){}
virtual void fun()
{
cout<<"Der...";
pb.fun();
}
};
int main()
{
Der(Der(Base())).fun();
return 0;
}
Run this code,and the result shows “Der…Base…”! This is so amazing, I can’t figure it out why the result is not “Der…Der…Base” which is logically right?!
Then I replace the member in class Der Base&pb with Base*pb and change the code into legal, finnaly the output is right which is “Der…Der…Base”!
I debug the code and find that when I use Base&pb, the constructor of Der only ran once while use Base*pb, the constructor ran twice correctly!
Any one who can explain to me what had happened and why?
In
Der(Der(Base())).fun()expression the innerDer(Base())yields anrvalue– the compiler optimizes the code by using copy elision and removes unnecessary copying of objects.