Please take a look at this code snippet
#include <iostream>
using namespace std;
class foo{
public:
virtual void v1(){
std::cout << "In Base this:" << std::hex << this << "\n";
}
};
class bar:public foo{
public:
void v1() {
std::cout << "In Derived this:" << std::hex << this << "\n";
}
};
int main() {
bar a, b, c;
static_cast<foo*>(&a)->v1();
static_cast<foo*>(&b)->v1();
static_cast<foo*>(&c)->v1();
static_cast<foo>(b).v1();
static_cast<foo>(b).v1();
return 0;
}
The output is
In Derived this:0x7ffe8a9e8890
In Derived this:0x7ffe8a9e88a0
In Derived this:0x7ffe8a9e88b0
In Base this:0x7ffe8a9e88c0
In Base this:0x7ffe8a9e88c0
As evident from value of this
pointer static_cast<foo>(b)
creates a completely new variable.
Moreover, further calls to static_cast<foo>(b)
refer to the previously created variable.
Could someone explain this behavior.
EDIT:
From the comments I get why static_cast<foo>(b)
would create a new variable. Still what I could not understand is that why multiple calls to static_cast<foo>(b)
refer to the same variable. Is is a compiler optimization ?