Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to instantiate different child classes conditionally?
    text
    copied!<p>For example, in the main function, I want to get the user's input. Depending on the input, I will create either a <code>Rectangle</code> or a <code>Circle</code>, which are child classes of <code>Object</code>. If there's no input (or unknown), then I will just create a generic object. </p> <pre><code>class Object { public: Object(); void Draw(); private: .... }; class Rectangle:public Object { public: Rectangle(); .... //it might have some additional functions private: .... }; class Circle:public Object { public: Circle(); .... //it might have some additional functions private: .... }; </code></pre> <p>main function:</p> <pre><code>string objType; getline(cin, objType); if (!objType.compare("Rectangle")) Rectangle obj; else if (!objType.compare("Circle")) Circle obj; else Object obj; obj.Draw(); </code></pre> <p>Of course, the code above won't work because I can't instantiate an object inside an If statement. So i tried something like this.</p> <pre><code>Object obj; if (!objType.compare("Rectangle")) obj = Rectangle(); else if (!objType.compare("Circle")) obj = Circle(); obj.Draw(); </code></pre> <p>This code would compile, but it won't do what I want. For some reason, the object was not initiated the way the child class should (for example, I set the some Object's member variables, specifically, a vector, differently in the child classes). However, when I put a break point at the Child class constructor, it did run through there. </p> <p>So how should I put instantiate Objects as its child classes in some if-statements??</p>
 

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