Search code examples
c++eclipseclassinitializationeclipse-cdt

Incorrect output and variables not initializing in constructor with Eclipse CDT


Can someone please explain to me why this code is not working in Eclipse CDT? When I run the program, the output is "310598136." I am also getting an error on line 7 that says "'Member x (and y) was not initialized in this constructor" but I have no idea why they are not initializing when I have the variables in the constructor and memory allocated in the private section of the class. Can someone please tell me what I am doing wrong?

#include <iostream>
using namespace std;

class Rectangle
{
public:
    Rectangle(int a, int b)
    {
        a = x;
        b = y;
    }
    int getArea();
private:
    int x;
    int y;
};

int Rectangle::getArea()
{
    return x * y;
}

int main()
{

    Rectangle bob(2,3);

    cout << bob.getArea();

    return 0;
}

Solution

  • You've swapped the order of your variable in the constructor.

    Change it to

    Rectangle(int a, int b) : x(a), y(b) {}
    

    Or, better

    Rectangle(int x, int y) : x(x), y(y) {}
    

    C++ is smart enough that you can use the same name in the parameter list as the member variables, and when you're just copying the value, you might as well do that -- it communicates very clearly what that parameter is for.

    Always remember to initialize your member variables in the order your declare them in the class.