Upcasting in C++
Upcasting
Upcasting allows public inheritance without the need of an explicit type cast.
Upcasting is a process of converting the derived class pointer to base class pointer so that anything that we can do on the base object can also be done on the derived class object.
Both upcasting and downcasting gives it possible to write complex programs with a simple syntax
Example program to demonstrate upcasting in C ++
#include <iostream> using namespace std; class parent //parent class { public: void show() { cout << "Base class\n"; } }; class child:public parent //child class { public: void show() { cout << "Derived Class\n"; } }; int main() { parent* p; //Base class pointer child c; //Derived class object p = &c; //assign child reference to parent class pointer c.show(); //Late Binding Ocuurs p->show(); return 0; }
Output
Derived class Base class
Upcasting allows treating a derived type as if it was its base type i.e any changes made on derived will also show an effect on the base class
If you do upcasting you can call only access to those properties that are inherited or overridden from base class, child class properties cannot be accessible.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment