The concept behind the “upcast”.

d_arin100's Avatar author of The concept behind the “upcast”.
This is an article on The concept behind the “upcast”. in C.

Introduction



The aim of this article is to explain the upcasting. Before going through this article I expect people have some preliminary idea about inheritance mechanism.

Background



The term upcasting comes from the class inheritance diagram. In the class inheritance diagram we generally draw the base class in the top and the derived class grows downward.
Code:
 
--------------------
|       Base       |
--------------------
          |
--------------------
|      Derived     |
--------------------
Since the casting from derived class to base class moves upwardin the inheritance diagram, so it is generally referred to as upcasting. The compiler allows upcasting because this type of cast is from specific type to a more generic type. Upcasting is safe but one thing that can happen for this upcast is object slicing (Lose of data and member function) .

The code



Code: Cpp
Code:
#include <iostream>
using namespace std;
 
class Base 
{
public:
 void Information()
 {
 cout << "We are in Base Information" <<endl;
 }
};
 
class Derived : public Base 
{
 void Information() 
 {
 cout << "We are in Derived Information" <<endl;
 }
};
 
void Generic(Base &base) 
{ 
 base.Information();
}
 
int main() {
 Derived derived;
 Generic(derived); /// Upcasting
 return 0;
}
Prevent object slicing in pass by value mechanism
Go4Expert Founder
3Oct2009,17:06   #2
shabbir's Avatar
Nomination for Article of the month - Sep 2009 Started. Nominate this article.
Newbie Member
19Oct2009,15:43   #3
kilstima's Avatar
Out of the many posts, this one attract my attention. I believe it is possible for anyone to participate.
Excellent ! I like it very much.
Go4Expert Founder
19Oct2009,21:36   #4
shabbir's Avatar
Nomination Closed and Voting started for Article of the month - Sep 2009. You can vote for this Article
Newbie Member
3Nov2009,11:36   #5
bibtrita's Avatar
15 minutes till showtime!
Newbie Member
4Nov2009,12:44   #6
sulscrishri's Avatar
Good work !
Very cool, looking great so far. Keep going, I wanna see it finished!
Banned
15Nov2009,06:07   #7
rasd123's Avatar
Hello, this is great article. I have blog and I thanks to say you thanks. Regards!