Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>C++, like Java, is a statically typed and statically scoped language. This means that the type and lifetime of variables must be known at compilation time.</p> <blockquote> <p>In java I always thought after a class is declared you can call its construtor at any time, but I have no idea how to do that in C++.</p> </blockquote> <p>This is not different from Java. In Java, what you're attempting would be equivalent to doing:</p> <pre><code>MyClass c; if (cond) { MyClass c = new MyClass(1); } else { MyClass c = new MyClass(2); } </code></pre> <p>This has <em>nothing</em> to do with calling constructors. It has to do with the fact that you're <em>declaring</em> new variables in nested scopes, and they are completely independent of variables of the same name in outer scopes.</p> <p>If you need runtime polymorphism, then (by definition), you actually need to use polymorphism. That is, you need to create a common base class with virtual functions:</p> <pre><code>class SimpleVectorBase { public: SimpleVectorBase() { } virtual ~SimpleVectorBase() { } virtual int size() const { return length; } // ... etc. ... private: int length; } template &lt;class T&gt; class SimpleVector : public SimpleVectorBase { // ... } int main() { // ... SimpleVectorBase* list1; if (dType == 0) { list1 = new SimpleVector&lt;int&gt;(dataSize); } else if (dType == 1) { list1 = new SimpleVector&lt;double&gt;(dataSize); } else { list1 = new SimpleVector&lt;string&gt;(dataSize); } // ... } </code></pre> <p>However, doing this won't really help you with your <code>for</code> loop. In your particular case, you probably would be better off templatizing the whole thing:</p> <pre><code>template&lt;typename T&gt; void doWork(int dataSize) { SimpleVector&lt;T&gt; list1(dataSize); std::cout &lt;&lt; "Please enter the data:" &lt;&lt; std::endl; for (int i = 0; i &lt; dataSize; i++) { std::cin &gt;&gt; list1[i]; } // ... Do other stuff with list1 ... } </code></pre> <p>and then your <code>main()</code> function would do:</p> <pre><code>if (dType == 0) { doWork&lt;int&gt;(dataSize); } else if (dType == 1) { doWork&lt;double&gt;(dataSize); } else { doWork&lt;string&gt;(dataSize); } </code></pre>
    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.
 

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