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
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Nomination for Article of the month - Sep 2009 Started. Nominate this article.
0
kilstima's Avatar, Join Date: Oct 2009
Newbie Member
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.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Nomination Closed and Voting started for Article of the month - Sep 2009. You can vote for this Article
0
bibtrita's Avatar, Join Date: Nov 2009
Newbie Member
15 minutes till showtime!
0
sulscrishri's Avatar, Join Date: Nov 2009
Newbie Member
Good work !
Very cool, looking great so far. Keep going, I wanna see it finished!
0
rasd123's Avatar
Banned
Hello, this is great article. I have blog and I thanks to say you thanks. Regards!