1

i have a problem:

variable 'MySet::group' is uninitialized. always initialize a member variable (type.6)

i dont understand what is the mistake, it seems to me that the variable is intizialize.

this the Source file

 MySet::MySet()
{   
    int* group = NULL;
}

this is Header File

class MySet
{
private:
    int* group;
    int size;

 public:
    MySet();                          //defult- creating an empty group
dana12
  • 11
  • 4

2 Answers2

1

MySet::group (the class member) is not initialized. In constructor you initialize a local variable, which dies as soon as this constructor finishes.

Change it to

MySet::MySet()
{   
    group = NULL;
}

Or better, using member initializer list

MySet::MySet() : group {NULL}
{   
}
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
  • it still dont initialize MySet::MySet() { group = { NULL }; } – dana12 Aug 24 '20 at 08:46
  • @NikaTatikishvili Can you explain something more? The second snippet should definitely fix this warning. The first snippet - it depends on the code analyzer. Technically it doesn't *initialize* the variable. It is first uninitialized and then assigned. And `size` is also uninitialized, you may get a warning from that too. – Yksisarvinen Aug 24 '20 at 09:03
0

What you're doing is declaring and initializing a local variable that happens to have the same name as the member.

There are two possible ways to initialize a member variable.

The traditional way is to use the constructor's initializer list:

MySet::MySet() : group(nullptr) 
{
}

A more modern method (since C++11) is to provide an initializer in the member's declaration instead:

class MySet
{
    // ...
    int* group = nullptr;
    // ...
};

If you write this:

MySet::MySet() 
{
    group = nullptr;
}

it's not an initialization but an assignment.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82