C++ Programs Upcasting and Downcasting
Upcasting and downcasting are two concepts in C++ that relate to the relationship between classes and their objects.
Syntax
// Upcasting
BaseClass *ptr = new DerivedClass;
// Downcasting
DerivedClass *ptr = dynamic_cast<DerivedClass*>(base_ptr);
Example
#include <iostream>
using namespace std;
class Animal {
public:
void speak() {
cout << "Animal speaks" << endl;
}
};
class Cat : public Animal {
public:
void speak() {
cout << "Meow" << endl;
}
};
int main() {
Animal *animal_ptr = new Cat();
animal_ptr->speak(); // Output: "Animal speaks"
Cat *cat_ptr = dynamic_cast<Cat*>(animal_ptr);
cat_ptr->speak(); // Output: "Meow"
return 0;
}
Output
Animal speaks
Meow
Explanation
In the above example, we have two classes - Animal and Cat. Cat is a subclass of Animal.
We create an object of the Cat class and store its address in a pointer of the Animal class. This is upcasting. When we call the speak() function using this pointer, it calls the function of the Animal class.
Next, we create another pointer of the Cat class and use the dynamic_cast operator to cast the animal_ptr pointer to a pointer of the Cat class. This is downcasting. Now when we call the speak() function using this pointer, it calls the function of the Cat class.
Use
Upcasting and downcasting allow us to treat an object of a derived class as an object of its base class and vice versa. This is useful when we want to use a general class to refer to a specific instance of a subclass.
Downcasting is particularly useful when we want to access specific attributes or methods that are defined only in the derived class.
Important Points
- Upcasting is when we cast an object of a derived class to an object of its base class.
- Downcasting is when we cast an object of a base class to an object of its derived class.
- Downcasting can be achieved using the dynamic_cast operator.
- Downcasting is unsafe, and we should always check if the cast is valid before using the pointer.
Summary
In summary, upcasting and downcasting are two concepts in C++ that allow us to treat an object of a derived class as an object of its base class and vice versa. Downcasting can be achieved using the dynamic_cast operator and is useful when we want to access specific attributes or methods that are defined only in the derived class. Downcasting is unsafe, and we should always check if the cast is valid before using the pointer.