Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Why do you expect that to work? You can't treat a <code>Base</code> object as if it were a <code>Child</code> object, because the <code>Child</code> class might have all sorts of additional data that <code>Base</code> does not.</p> <p>In order to get the effect you're looking for, there are two ways to do it:</p> <p>The first way, and probably the best idea, is to move the logic from <code>createBase</code> into the <code>Base</code> constructor. The <code>Base</code> constructor will run whether you're creating a <code>Base</code> or something derived from it. It looks like you're trying to do the work of initializing the base object, and that's exactly what constructors are for!</p> <p>If for some reason this will not work in your case, the other option is to create a protected <code>initialize</code> method in <code>Base</code> which accepts a <code>Base*</code> and does all the work that you are currently doing in <code>createBase</code>, e.g.</p> <pre><code>class Base { public: static Base* createBase() { Base* b = new Base(); initialize(b); return b; } protected: static void initialize(Base* b) { ... //does a lot of weird things } } class Child : public Base { public: static Child* createChild() { Child *c = new Child(); initialize(c): return c; } } </code></pre> <p>Note that this works since, while you can't treat a <code>Base*</code> as if it were a <code>Child*</code>, you <em>can</em> go the other way and treat a <code>Child*</code> as if it were a <code>Base*</code>, because the <code>Child</code> class is guaranteed to have at least everything that the <code>Base</code> class does, due to the nature of inheritance.</p> <p><strong>Edit:</strong> I saw you post in a comment to another answer that you cannot modify the definition of <code>Base</code>. In that case, you are completely out of luck and you will have to accept the need to copy-and-paste, given the restrictions in play. You are not going to be able to call <code>createBase</code> and get back a pointer to an object of any type other than <code>Base</code> if you cannot modify its code.</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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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