简体   繁体   中英

Static Cast from ( Base Reference to Base Object ) to ( Derived Class Reference)

In the main function below , the first static_cast is valid as i am trying to cast a (base class reference to Derived1 class) to a derived reference But why is the second cast printing with the values, though it prints junk value for d2.y , i assumed it should be a warning or compilation error. How is a base reference to base object picking derived class's value ( d2.y in this case, i can also assign a value to it )

Can someone please explain what happens in these two cases .

class Base1
{
 public:
  Base1()
  {
    x = 999;
  }
 int x;
};

class Derived1: public Base1
{
  public:
  Derived1()
 {
    y = 1000;
 }
  int y;
};

int main()
{
 Derived1 d;
 std::cout << d.x << " " << d.y << std::endl;
 Base1& b = d;
 Base1 b1;

 Base1 & b2 = b1;

 Derived1& d1 = static_cast<Derived1&>(b);
 Derived1& d2 = static_cast<Derived1&>(b2);

 std::cout << d1.x << " " << d1.y << std::endl;
 std::cout << d2.x << " " << d2.y << std::endl;

 return 0;     
}

A static_cast is a promise from you to the compiler that the base class really is a derived class -- no need for the computer to double check. You're telling the compiler that you, as the programmer, know something the compiler cannot know which guarantees this to be true. So when the instruction comes for the CPU to go access a value at the memory address where the member of the derived type should be, it goes off into some memory that can contain pretty much anything, just like you told it to.

Except for very simple cases, the compiler cannot know what a reference to a base type really has. That's why dynamic_cast exists (but it requires additional information -- the vtable -- in order to check).

static_cast will cause a compile time error if two types cannot possibly be related, but if they are in the same inheritance chain, you can do all sorts of bad with an invalid static_cast .

When you start thinking about C/C++ types as simply definitions of offsets into memory, many of the behaviors and syntax requirements start making more sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM