Upcasting in C++
Upcasting in C++
As discussed earlier, if we inherit a class from another class then the class which is inherited is called parent class and the which inherits the parent class is called child class. After inheritance is done then we can create the objects of parent class or objects of child class.
In C++ Sometimes it is required that the pointer object of parent class should point to the object of the child class. This is called upcasting. In upcasting is converting a child class’s reference to parent class’s reference.
It is some sort of polymorphism where the same object of parent class can refer to the parent class at one part of the program and will refer to the address of its child class at another part of the program when the address of the child’s class is stored in the pointer object of the parent class. The following code shows the concept of upcasring.
In the above code, class Person is inherited by class Student so class Person is parent and class Student is child class. At line 21, we can see that a pointer variable of class Person points to the object of its child class. Once the reference is established the pointer object of parent class (‘p’ in this case) can access the members of its child class (‘s’ in this case). In other words you can say that p behaves like the object of Student class accessing all the members of Student class
Advantages of Upcasting
One of the most powerful feature of object oriented programming is polymorphism. We will discuss polymorphism in detail in the next tutorial. Polymorphism can be implemented in a number of ways in C++. Upcasting is one of them.
In some languages like Java, upcasting is done automatically but in C++ it is done explicitly. Just like upcasting, object oriented programming also support down-casting. This feature will be discussed in a later tutorial.
More Related Articles For You
- What is C++
- C++ and Object Oriented Programming OOPS concepts
- Syntax and Structure of C++ program
- Data Types in C++
- C++ Variables
- Types of operators in C++
- Decision making in C++
- C++ Loop Types
- Storage Classes in C++
- Functions in C++
- Classes and Objects in C++
- Access controls in C++ Classes
- Defining Class and Object in C++
- Accessing Public and Private Data Members in C++
- Member Functions in Classes
- Types of Member Functions in C++
- Inline Functions in C++
- Namespaces in C++
- Function Overloading in Classes in C++
- Constructors and Destructors in C++
- Static Keywords in C++
- Const Keyword in C++ Programming
- References in C++
- Copy Constructor in C++
- Pointer to Members in C++ Classes
- Introduction to Inheritance
- Types of Inheritance
- Order of Constructor Call in Inheritance
- Function Overriding in C++
- Virtual Functions in C++
- Abstract Class and Pure Virtual Functions in C++
- Virtual Destructors in C++
- Operator Overloading in C++
C++ Tutorial
C++ Quizzes