Note that there are some explanatory texts on larger screens.

plurals
  1. POInitializing non static member : C++ and Java comparison
    primarykey
    data
    text
    <p>I am from C++ background and learning Java.</p> <p>In C++ we can not initialize a non static member inside the class definition as shown below:</p> <pre><code>#include &lt;iostream&gt; using namespace std; class myClass{ int i=10;//Error public: void set_i() { i=10; } void get_i() { cout &lt;&lt; i &lt;&lt; endl; } }; int main() { myClass ob; ob.set_i(); ob.get_i(); return 0; } </code></pre> <p>Throws compilation error:</p> <pre><code>$ g++ -Wall Test.cpp -o Test Test.cpp:8: error: ISO C++ forbids initialization of member `i' Test.cpp:8: error: making `i' static Test.cpp:8: error: ISO C++ forbids in-class initialization of non-const static member `i' </code></pre> <p>But it is allowed in Java:</p> <pre><code>class Test{ private int i=10; //No Error public static void main(String[] args) { Test t= new Test(); System.out.println(t.i); } } </code></pre> <p>It compiles and runs successfully in JAVA.</p> <p>Can someone tell me the reason for this difference?</p> <p>Thanks</p> <p>@Those who flagged this question as un-useful. This is a valid question:</p> <p>Based on below reference: <a href="http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fcplr038.htm" rel="nofollow">http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fcplr038.htm</a></p> <p>"Once you define a static data member, it exists even though no objects of the static data member's class exist."</p> <p>It means then: C++ does not allow this because there is no instance created for that data variable unless an object of the class is created first. If that is not the case with java, it means an instance of a data member does exist even if no object of that class has been created.</p> <p>And also Java takes C++ as base, so there must be some concrete reason to make this difference between the two languages.</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