jweinst1
8/15/2017 - 11:07 PM

C++ class example of down or upcasting

C++ class example of down or upcasting

#include <iostream>

//c++ down/up casting clases example
//added constructor example

//base class
class Base
{
  public:
  int type;
  Base* next;
  Base* prev;
  
  int getType()
  {
    return type;
  }
  
  void setType(int t)
  {
    type = t;
  }
};

class IntObj: public Base
{
  public:
  long value;
  //constructor with init list
  IntObj(long val): value(val)
  {
    type = 3;
  }
  
  long getValue()
  {
    return value;
  }
  
  void setValue(long val)
  {
    value = val;
  }
};



int main() {
  Base* b = new IntObj(8);
  std::cout << b->getType() << "\n";
  std::cout << b->type << "\n";
  //static cast needed for down casting
  IntObj* i = static_cast<IntObj*>(b);
  //or a reinterpret_cast 
  IntObj* j = reinterpret_cast<IntObj*>(b);
  std::cout << j->getValue() << "\n";
  std::cout << j->type << "\n";
}