Skip to content

Instantly share code, notes, and snippets.

@tejainece
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save tejainece/33f465829b55753623f0 to your computer and use it in GitHub Desktop.

Select an option

Save tejainece/33f465829b55753623f0 to your computer and use it in GitHub Desktop.
C++: Static and dynamic cast
#include <iostream>
using namespace std;
class Base {
public:
virtual void print() {
cout << "in base" << endl;
}
virtual ~Base() {
cout << "Boom destructed" << endl;
}
};
class Derived1 : public Base {
public:
int var1 = 1;
virtual void print() {
cout << "1" << endl;
}
};
class Derived2 : public Base {
public:
int var1 = 2;
virtual void print() {
cout << "2" << endl;
}
};
Derived1 *d1p1 = dynamic_cast<Derived1 *>(bp1);
if(d1p1 != NULL) {
d1p1->print();
} else {
cout << "Couldn't cast" << endl;
}
Base b;
Derived1 d1;
Base *bp1 = dynamic_cast<Base *>(&d1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment