开发者

Object Slicing in c++

    class Base
    {  
         int iBase;

      public:           
         virtual void display()
         {
            cout<<"I am a Base Class"<<endl;
         }  开发者_高级运维      
    };

    class Derived : public Base
    { 
        int iDerived;

     public:
        Derived()
        {
            cout<<"In Derived Default Constructor"<<endl;
            iDerived=10;
        }   

        void display()
        {
            cout<<"I am in Derived Class"<<endl;
            cout<<"value of iDerived  :"<<iDerived<<endl;
            iDerived=100;
            cout<<"value of iDerived  :"<<iDerived<<endl;
        }                
   };

In MAIN:

     Base *varBase;
     Derived varDerived;

     varBase = &varDerived;
     varBase->display();
     varBase->iDerived=10; // Error: iDerived is not a member of Base: ?????

Hi all,

I am trying to understand the Object Slicing and trying with some sample programs.

I read somewhere with the pointer reference Objcet Slicing will not happen.

But with below example I am noticing that iDerived is not accessible from Base pointer(varBase), But from the virtual display method of class I can access even though it's not in the local scope of display method.

Now my question is:

  1. Why I am able to access the iDerived variable only with virtual function, is this proper ?
  2. How to avoid object slicing.


Your example code doesn't involve slicing at all. All you have done is invoke basic polymorphism. By declaring Base::display() as virtual and by calling display() on a Base *, you have asked it to dynamically call the member function in the actual type of the object being pointed to, which is Derived. The member variables of Derived are within the scope of Derived::display(), so that is why it compiles and works.

However, you can only directly access member variables (or functions) declared in Base via a pointer-to-Base. That is why varBase->iDerived does not compile.

Slicing normally involves something equivalent to:

Derived d;
Base b = (Base)d;

By explicitly assigning/initializing a Base object, all the Derived-specific members will have been lost (i.e. they have been "sliced" away).

This stuff is relatively fundamental; I would suggest picking up a decent book on C++. There is a list of good ones here: The Definitive C++ Book Guide and List.


C++ has virtual functions, but no virtual data.

You could add the following to simulate it:

class Base {
  // What you had before
  virtual int getAnInt() const = 0; // =0 means that Derived must implement this
};
class Derived {
  // What you had before
  virtual int getAnInt() const { return iDerived; }
};

Object slicing is entirely unrelated, and doesn't happen in your example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜