Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy and Where do we use down casting?
    primarykey
    data
    text
    <p>Are there any cases where we do down casting of objects?</p> <p>If we do, why?</p> <p>I have observed a way of hiding implementation using the below code. Is this the correct way to do? Is there any better way to achieve the same.</p> <pre><code>class A{ public: A(); virtual ~A(); //exposed virtual functions }; class AImpl : public A{ public: AImpl(A *obj); virtual ~AImpl(); //exposed virtual functions++ }; class Helper{ //utility class so i am making constructor and assignment operator as private public: static bool doWork(A *obj){ AImpl *objImpl = dynamic_cast&lt;AImpl *&gt; (obj); return doWork(objImpl); // some internal function } private: Helper(); Helper(const Helper&amp; obj); const Helper&amp; operator=(const Helper&amp; obj); }; </code></pre> <p>The question still does not makes sense. I agree. I still have not figured out a proper way of hiding the implementation details from the client.</p> <p><strong>UncleBens</strong> I termed this thing wrongly as Object slicing. Basically, I was referring to this (Object Slicing) as the information related to derived part is missing.</p> <p><strong>S.Soni</strong> Thanks for giving a wonderful explaination. Now, I can really put forward question.</p> <p>Consider a clients perspective. The only class which are visible to him is class A and the Helper class (because I have hidden implementation behind AImpl</p> <p>Client has to write the following code as he is unaware of AImpl class</p> <pre><code>int main(){ A *a = new A(); Helper.doWork(a); // ... } </code></pre> <p>As you said AImpl * in this case will actually be pointing to the base class object, which is wrong (you have explained it with a great example), so this approach of hiding implementation is not correct. </p> <p>Any attempt to access a derived class member function will result in a crash (and correctly so).</p> <p>How should I go about hiding the implementation in this case? This is a design problem now?</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.
    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