Difference between revisions of "CPP/Classes/DownCasting"

From ProgrammingExamples
< CPP
Jump to: navigation, search
(DownCasting.cpp)
 
(Threads.cpp)
Line 41: Line 41:
 
   else
 
   else
 
     std::cout << "Could not down-cast ptr2 to Derived1 class!" << std::endl;
 
     std::cout << "Could not down-cast ptr2 to Derived1 class!" << std::endl;
 +
 +
  delete ptr1;
 +
  delete ptr2;
 +
  //DO NOT DELETE ptr3 or ptr4 because they point to the same objects as ptr1 and ptr2, i.e., casting does not copy the pointed-to objects.
 +
  return 0;
 
};
 
};
  

Revision as of 22:13, 23 November 2010

Threads.cpp

#include <iostream>
 
class Base {
  public:
    virtual ~Base() { }; //at least one virtual function is necessary in the base class.
};
 
class Derived1 : public Base {
  public:
    Derived1() { };
    ~Derived1() { }; 
    void print(); //notice that print does not exist in Base.
};
 
class Derived2 : public Base {
  public:
    Derived2() { };
    ~Derived2() { };
    void print(); //notice that print does not exist in Base.
};
 
int main() {
  Base* ptr1 = new Derived1();
  Base* ptr2 = new Derived2();
 
  //now we can try a dynamic down cast:
  Derived1* ptr3 = dynamic_cast<Derived1*>(ptr1);
  //if successful, ptr3 will be non-NULL:
  if(ptr3)
    ptr3->print();
  else
    std::cout << "Could not down-cast ptr1 to Derived1 class!" << std::endl;
 
  //if we try with ptr2 it will not work because ptr2 is pointing to an object of class Derived2.
  Derived1* ptr4 = dynamic_cast<Derived1*>(ptr2);
  //if successful, ptr4 will be non-NULL:
  if(ptr4)
    ptr4->print();
  else
    std::cout << "Could not down-cast ptr2 to Derived1 class!" << std::endl;
 
  delete ptr1;
  delete ptr2;
  //DO NOT DELETE ptr3 or ptr4 because they point to the same objects as ptr1 and ptr2, i.e., casting does not copy the pointed-to objects.
  return 0;
};
 
void Derived1::print() {
  std::cout << "Down cast to Derived1 was successful!" << std::endl;
};
 
void Derived2::print() {
  std::cout << "Down cast to Derived2 was successful!" << std::endl;
};