Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is 'object slice' needed in C++ ? Why it is allowed ? For more bugs?
    primarykey
    data
    text
    <p>Why C++ standard allow object slice ? </p> <p>Please don't explain c++ object slice concept to me as I knew that.</p> <p>I am just wondering what's the intention behind this c++ feature(object slice) design ? </p> <p>To get novice more bugs?</p> <p>Wouldn't it be more type safe for c++ to prevent object slice ?</p> <p>Below is just a standard and basic slice example:</p> <pre><code>class Base{ public: virtual void message() { MSG("Base "); } private: int m_base; }; class Derived : public Base{ public: void message() { MSG("Derived "); } private: int m_derive; }; int main (void) { Derived dObj; //dObj get the WELL KNOWN c++ slicing below //evilDerivedOjb is just a Base object that cannot access m_derive Base evilDerivedOjb = dObj; //evilDerivedObj is type Base evilDerivedOjb.message(); //print "Baes" here of course just as c++ standard says } </code></pre> <p>Thanks in advance.</p> <p>================================================================================= After reading all the answers and comments I think I should express my question better in the first place but here it comes:</p> <p>When there is a is-a relationship(public inheritnace), instead of private/protected inheritance , you can do the following:</p> <pre><code>class Base{ public: virtual void foo(){MSG("Base::foo");} }; class Derived : public Base{ public: virtual void foo(){MSG("Derived::foo");} }; int main (void) { Base b; Derived d; b = d; //1 Base * pB = new Derived(); //2 Base&amp; rB = d; //3 b.foo(); //Base::foo pB-&gt;foo(); //Derived::foo rB.foo(); //Derived::foo } </code></pre> <p>It's well known that only 2 &amp; 3 works polymorphically while one is the infamous object slicing which produce nothing but a bug !</p> <p>Note 1, 2 and 3 <strong>NEED</strong> is-a relationship to work.<br> If you are using private/protect inheritance, you will get compile error for all of them :</p> <pre><code>'type cast' : conversion from 'Derived *' to 'const Base &amp;' exists, but is inaccessible 'type cast' : conversion from 'Derived *' to 'Base *' exists, but is inaccessible 'type cast' : conversion from 'Derived *' to 'Base &amp;' exists, but is inaccessible </code></pre> <p>So my question(original intention) was to ask would it be better if c++ standard make 1 a compile error while keep allowing 2 and 3 ?</p> <p>Hope I have expressed my question better this time.</p> <p>Thanks</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload