ChrisM
ChrisM

Reputation: 209

C++ Problem declaring multiple object instances on the same line

For a homework assignment, I'm having a hard time understanding the behavior when the main class is instantiating two objects of the same class on the same line as follows. Note that the object of the assignment is for the class to behave like an int:

main () {
  MyClass x,y = 5;
  cout << "x = " << x << endl; // outputs x = 0...why not 5???
  cout << "y = " << y << endl; // outputs y = 5
}

and here's header file class definition:

class MyClass {
   public:
      MyClass(int initValue = 0); //constructor
      operator int() {return myValue}; //conversion operator to int
   private:
      int myValue;
}

and finally, my source file:

#include "MyClass.h"

MyClass::MyClass(int initValue) {
   myValue = initValue;
}

Why doesn't x get initialized with the value of 5 like y does?

Upvotes: 1

Views: 5574

Answers (1)

templatetypedef
templatetypedef

Reputation: 372972

The problem is that C++ is parsing

MyClass x,y = 5;

As if you had written

MyClass x;
MyClass y = 5;

And so x is getting default-initialized rather than initialized with 5. To fix this, change the line to read

MyClass x = 5, y = 5;

Upvotes: 9

Related Questions