July 10, 2011

Object Slicing in c++

"If b is a base class pointer and d is a derived class pointer then b=d will copy only the base class contents and remove the derived class contents.This is known as Object Slicing and should be avoided."


 class bc  
 {  
 public:  
 int a;  
 float b;  
 };  
 class dc : public bc  
 {  
 public:  
 char c;  
 };  
 main()  
 {  
 bc Bobj; //Bobj contains int a and float b  
 dc Dobj; //Dobj contains int a, float b and char c  
 Bobj=Dobj; // when we assign dc class obj to a bc class obj it slices of dc portion of obj so a and b get copied into a and b of Bobj and char c does not get copied in effect Dobj got sliced  
 }