Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   The concept behind the “upcast”. (http://www.go4expert.com/articles/concept-upcast-t19632/)

d_arin100 30Sep2009 16:37

The concept behind the “upcast”.
 

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

shabbir 3Oct2009 17:06

Re: The concept behind the “upcast”.
 
Nomination for Article of the month - Sep 2009 Started. Nominate this article.

kilstima 19Oct2009 15:43

Re: The concept behind the “upcast”.
 
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.

shabbir 19Oct2009 21:36

Re: The concept behind the “upcast”.
 
Nomination Closed and Voting started for Article of the month - Sep 2009. You can vote for this Article

bibtrita 3Nov2009 11:36

Re: The concept behind the “upcast”.
 
15 minutes till showtime!

sulscrishri 4Nov2009 12:44

Re: The concept behind the “upcast”.
 
Good work !
Very cool, looking great so far. Keep going, I wanna see it finished!:surprised

rasd123 15Nov2009 06:07

Re: The concept behind the “upcast”.
 
Hello, this is great article. I have blog and I thanks to say you thanks. Regards!


All times are GMT +5.5. The time now is 15:25.