Raicha
Raicha

Reputation: 138

Uninitialised local variable from class

When I'm trying to access classes public variable (in this case trying to input text row) it shows that it's uninitialized. However, I declared it in class as a public variable. I know that's some dummy mistake, but can't find it :D

#include <iostream>
#include <conio.h>

using namespace std;

class stringlength {
private:
    int lengt;
public:
    char * row;

    int len()
    {
        for (int i = 0, lengt = 0; (*(row + i) != '\0'); i++, lengt++) {}
        return lengt;
    }
};
int main()
{
    stringlength test;

    cout << "Enter a string:";
    cin >> test.row;
    cout << "Length is: " << test.len();
    _getch();

}

This program is expected to give a length of the inputted row (like strlen function) Error is:

Error C4700 uninitialized local variable 'test' used

Thanks for help ;)

Upvotes: 0

Views: 182

Answers (1)

Michael Chourdakis
Michael Chourdakis

Reputation: 11178

Declaring the variable does not mean that it's initialized.

Initialize it in a constructor, or just char * row = nullptr; (if 0 is the intended initialization).

Same for all the variables that you have which have no constructors.

Edit: in this specific case you need to initialize to a new pointer char * row = new char[...]

Upvotes: 3

Related Questions