
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Dynamic Cast and Static Cast in C++
static_cast: This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. This can cast related type classes. If the types are not same it will generate some error.
Example
#include<iostream> using namespace std; class Base {}; class Derived : public Base {}; class MyClass {}; main(){ Derived* d = new Derived; Base* b = static_cast<Base*>(d); // this line will work properly MyClass* x = static_cast<MyClass*>(d); // ERROR will be generated during compilation }
Output
[Error] invalid static_cast from type 'Derived*' to type 'MyClass*'
dynamic_cast: This cast is used for handling polymorphism. You only need to use it when you're casting to a derived class. This is exclusively to be used in inheritance when you cast from base class to derived class.
Example
#include<iostream> using namespace std; class MyClass1 { public: virtual void print()const { cout << "This is from MyClass1\n"; } }; class MyClass2 { public: virtual void print()const { cout << "This is from MyClass2\n"; } }; class MyClass3: public MyClass1, public MyClass2 { public: void print()const { cout << "This is from MyClass3\n"; } }; int main(){ MyClass1* a = new MyClass1; MyClass2* b = new MyClass2; MyClass3* c = new MyClass3; a -> print(); b -> print(); c -> print(); b = dynamic_cast< MyClass2*>(a); //This cast will be failed if (b) b->print(); else cout << "no MyClass2\n"; a = c; a -> print(); //Printing from MyClass3 b = dynamic_cast< MyClass2*>(a); //Successfully casting is done if (b) b -> print(); else cout << "no MyClass2\n"; }
Output
This is from MyClass1 This is from MyClass2 This is from MyClass3 no MyClass2 This is from MyClass3 This is from MyClass3
Advertisements