1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

The concept behind the “upcast”.

Discussion in 'C' started by d_arin100, Sep 30, 2009.

  1. d_arin100

    d_arin100 New Member

    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
     
  2. shabbir

    shabbir Administrator Staff Member

  3. kilstima

    kilstima New 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.
     
  4. shabbir

    shabbir Administrator Staff Member

  5. bibtrita

    bibtrita New Member

    15 minutes till showtime!
     
  6. sulscrishri

    sulscrishri New Member

    Good work !
    Very cool, looking great so far. Keep going, I wanna see it finished!:surprised
     
  7. rasd123

    rasd123 Banned

    Hello, this is great article. I have blog and I thanks to say you thanks. Regards!
     

Share This Page