what is object slicing?

Answer Posted / p govind rao

if an object of a derived class is assigned to a base class
object,the compiler accepts it.but it copies only the base
portion of the object


#include<iostream>
using namespace std;

class base
{
public:
int i,j;
base(){i=2;j=3;}
virtual void show(){cout<<"i = "<<i<<endl<<"j = "<<j<<endl;}
};

class derived :public base
{
public :
int k;
derived(){k=4;}
void show() {
base::show();
cout<<"k = "<<k<<endl;
}
};

int main()
{
base b;
derived d;
d.show();
b=d;

b.show();

return 0;
}

OutPut is
i = 2
j = 3
k = 4
---------------
i = 2
j = 3

here b contains i and j where as d contains i,j&k.On
assignment only i and j of the d get copied into i and j of
b. k doesnot be copied. on the effect object d got sliced.

Is This Answer Correct ?    12 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is abstraction in oop with example?

648


Whats oop mean?

601


What is meant by multiple inheritance?

742


How do you achieve polymorphism?

618


What is class and example?

571






What is purpose of inheritance?

645


How to use CMutex, CSemaphore in VC++ MFC

4335


What are the advantages of polymorphism?

577


What are the types of abstraction?

562


What are the three main types of variables?

604


How to hide the base class functionality in Inheritance?

640


Why do we use class?

638


What is static modifier?

636


What is overriding vs overloading?

590


Why multiple inheritance is not allowed?

586