Question:

Reason for the output of the following C++ program?

by  |  earlier

0 LIKES UnLike

include <iostream.h>

class myClass

{

public:

int x;

myClass()

{

x++;

}

};

main()

{

myClass obj1,obj2;

cout<<obj1.x<<"\t"<<obj2.x;

system("pause");

}

Why am i getting this output:

3 67

 Tags:

   Report

3 ANSWERS


  1. The display is from  the line:

             cout&lt;&lt;obj1.x&lt;&lt;&quot;\t&quot;&lt;&lt;obj2.x;

    which prints the value of the int x from both objects. Since you haven&#039;t initialised x to any particular value, it&#039;ll print the value of the memory location that x occupied, whatever that is.

    Try this:

    class myClass

    {

    public:

       int x = 0;

       myClass(int j)

       {

          x = ++j;

       }

    };

    main()

    {

       myClass obj1,obj2(10);

       cout&lt;&lt;obj1.x&lt;&lt;&quot;\t&quot;&lt;&lt;obj2.x;

       system(&quot;pause&quot;);

    }


  2. You never initiate the variable in myClass. You need set a value to x, after the obj1 and obj2 defined. Currently, the value is what in memory like a garbage.

    obj1.x = 1;

    obj2.x = 2;

    cout&lt;&lt;obj1.x&lt;&lt;&quot;\t&quot;&lt;&lt;obj2.x;

    Good luck,

    peng

    http://www.eptop.com


  3. include &lt;iostream.h&gt;

    class myClass

    {

    public:

    int x, j;

    myClass()

    {

    j=1 ;

    x=++j ;

    }

    };

    main()

    {

    myClass obj1,obj2;

    cout&lt;&lt;obj1.x&lt;&lt;&quot;\t&quot;&lt;&lt;obj2.x;

    system(&quot;pause&quot;);

    }

Question Stats

Latest activity: earlier.
This question has 3 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions