Search code examples
c++classinitializationstatic-methodsmember-functions

What does this error mean? C6001: using uninitialized memory 'Rect.'


Visual Studio gave this bizzare error: C6001: using uninitialized memory 'Rect.'

#include<iostream>
#include<cstring>
using namespace std;

class Rectangle
{public:
    int length, width;

    int Area(int length, int width)
    {
        return length * width;
    }
};

int main()
{
    Rectangle d1;
    d1.length = 5;
    d1.width = 10;

    cout << "d1 area=" << d1.length * d1.width << endl;

    Rectangle Rect;
    Rect.Area(Rect.length, Rect.width);

    return 0;
}

What is that mean and how to fix it?


Solution

  • The object Rect declared in this declaration

    Rectangle Rect;
    

    has uninitialized data members length and width.

    These uninitialized data members you are passing as arguments to the member function Area.

    Rect.Area(Rect.legth, Rect.width);
    

    So the call does not make a sense.

    You could write for example

    Rectangle Rect = { 5, 10 };
    std::cout << Rect.Area(Rect.legth, Rect.width) << '\n';
    

    Pay attention to that the function Area either should be a static member function or should use the data members length and width of the object.

    That is either it should be declared like

    static long long int Area(int length, int width)
    {
        return static_cast<long long int>( length ) * width;
    }
    

    or like

    long long int Area() const
    {
        return static_cast<long long int>( length ) * width;
    }