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
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.
Nomination Closed and Voting started for Article of the month - Sep 2009. You can vote for this Article