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.

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

    C++ Tutorial

    C++ Quizzes

 

Search

Shortcodes Ultimate

 
Follow Us
 
BGP