Static_cast & Dynamic_cast

static_cast:

  1. Conversions between integers, float, double, char and etc.

balance = static_cast<double>(cents);
char c;//0 <= c <= 10
digit = static_cast<int>(c) - static<int>('0');
  1. Downcast a base class pointer to a derived class pointer. It is fast and efficient(compile time), but it may crush if you do anything wrong. It is safer to use dynamic_cast.

//This is approved
​
Vehicle *p_vehicle = new Car("Ford", 2012);
Car* p_car = static_cast<Car*>(p_vehicle);
Car* p_car = dynamic_cast<Car*>(p_vehicle);
​
//This is not right
Vehicle *p_vehicle = new vehicle;
Car* p_car = static_cast<Car*>(p_vehicle);
//because a derived class belongs to the base class, but the base class does not belong to the derived class

Both p_car and p_vehicle contains the same memory address value. However it is the type of the variable that dictates which function the variable can do, not the variable's address value.

Dynamic_cast:

When function is declared as virtual in the base class, then the corresponding functions in the derived class will be declared as virtual too. But it is a good habit to add virtual in front of the functions in the derived class too.

down cast a base class pointer to a derived class pointer.

typical use:

Zebra * p_zebra = nullptr;
​
Elephant * p_elephant = nullptr;
​
Tiger * p_tiger = nullptr
​
Panda * p_panda  = nullptr;
​
for  ( int i = 0 ; i < kAnimalMax; i++ ) {
​
          // generic processing
​
         zoo[i]->Eat ( );
​
        zoo[i]->Drink ( );
​
        // specific processing
​
       if  ( (p_zebra = dynamic_cast <Zebra *> (zoo[i]))  != nullptr) {
​
              p_zebra->NibbleHair ( );
​
       } else if ((p_elephant = dynamic_cast <Elephant *> (zoo[i]))  != nullptr) {
​
                          p_elephant->Grumbling ( );
​
      } else if ((p_tiger = dynamic_cast <Tiger *> (zoo[i]))  != nullptr) {
​
                       p_tiger->Hunt ( );
​
       } else if ((p_panda= dynamic_cast <Panda *> (zoo[i]))  != nullptr) {
​
                          p_panda->JustSleep ( );
​
       }
​
} // end of for loop

When dynamic_cast a pointer, if the pointer is not that kind of pointer, it will yield nullptr. So, it is a great way to distinguish different types of pointer like above. You do not need to use dynamic_cast in all polymorphism.

PS. Some of the codes are from Foothill college CS2B Professor Tri Pham class. Awesome professor. I wrote this article because I am kind of confused of these two different cast in his class. I will delete the codes if I violate the copyright. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值