Object Slicing
In inheritance we can assign a derived class object to a base class object. But, a base class object cannot be assigned to a derived class object. When a derived class object is assigned to a base class object, extra features provided by the derived class will not be available. Such phenomenon is called object slicing.
Following program demonstrates object slicing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include<iostream> using namespace std; class A { protected: int x; public: void show() { cout << "x = " << x << endl; } }; class B: public A { protected: int y; public: B(int x, int y) { this -> x = x; this -> y = y; } void show() { cout << "x = " << x << endl; cout << "y = " << y << endl; } }; int main() { A objA; B objB(30, 20); objA = objB; //Assign derived class object to base class object objA.show(); return 0; } |
Output of the above program is as follows:
1 2 3 | x = 30 |
In the above program, when objA.show() is called, even though class B has variable y, we were not able to access it; which is treated as object slicing.
Pointer to Derived Class
A base class pointer can point to a derived class object. But, a derived class pointer can never point to a base class object. Following program demonstrates object slicing using a base class pointer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include<iostream> using namespace std; class A { protected: int x; public: void show() { cout << "x = " << x << endl; } }; class B: public A { protected: int y; public: B(int x, int y) { this -> x = x; this -> y = y; } void show() { cout << "x = " << x << endl; cout << "y = " << y << endl; } }; int main() { A * bptr; B objB(30, 20); bptr = & objB; //Assign derived class object to base class pointer bptr -> show(); return 0; } |
Output of the above program is as follows:
1 2 3 | x = 30 |
Take your time to comment on this article.