Don't need a cast to go up the inheritance hierarchy : cast « Class « C++






Don't need a cast to go up the inheritance hierarchy

  
class Base{
public:
  Base() {};
  virtual ~Base() {}
};

class Derived : public Base{
public:
  Derived() {}
  virtual ~Derived() {}
};

int main(int argc, char** argv)
{
  Base* b;
  Derived* d = new Derived();

  b = d; // Don.t need a cast to go up the inheritance hierarchy
  d = static_cast<Derived*>(b); // Need a cast to go down the hierarchy

  Base base;
  Derived derived;

  Base& br = base;
  Derived& dr = static_cast<Derived&>(br);

  int i = 3;
  double result = static_cast<double>(i) / 10;

  return (0);
}
  
    
  








Related examples in the same category

1.class type-casting
2.The const_cast operator is used to explicitly override const and/or volatile in a cast.
3.Use const_cast on a const reference.Use const_cast on a const reference.
4.The static_cast operator performs a nonpolymorphic cast.
5.The reinterpret_cast operator converts one type into a fundamentally different type.
6.The dynamic_cast performs a run-time cast that verifies the validity of a cast.
7.Replacing typeid with dynamic_cast