0

I have a simple class here with a variable. Why does it not return the value of the variable 10.5?

output

Test! -1.09356e+09

code

#include "iostream"

using namespace std;

class Txtbin{
    protected:
        float area;

    public:
        Txtbin();
        float get_area();
};

Txtbin::Txtbin(){
    float area = 10.5;
}

float Txtbin::get_area(){
    return area;
}

int main(int argc, char* argv[]){
    Txtbin a;
    cout << "Test! " << a.get_area() << endl;

    return 0;
}
3
  • Mine tells Test! 0. Commented Feb 27, 2016 at 18:18
  • Undefined behavior because you print the indeterminate value of an uninitialized member variable. Commented Feb 27, 2016 at 18:19
  • And that's why you compile with warnings, and pay attention to them. Commented Feb 27, 2016 at 18:33

2 Answers 2

5

This is creating a local variable, not initializing your member:

Txtbin::Txtbin(){
    float area = 10.5; // creates a variable called area that isn't used.
}

You should initialize your member like this

Txtbin::Txtbin()
: area(10.5)
{
}

Or perhaps directly in the class if you are using C++11 or newer:

class Txtbin{
    protected:
        float area = 10.5;

    public:
        Txtbin();
        float get_area();
};
Sign up to request clarification or add additional context in comments.

2 Comments

When I init the variable directly I get this txtbin.cpp:11:16: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 float area = 10.5;
@clarkk: That's right. I'm guessing you are using gcc. It doesn't use C++11 by default.
0

Your new area declaration here shadows the member.

Txtbin::Txtbin(){
    float area = 10.5;
}

If you enable more/all warnings, the compiler will probably tell you as much.

e.g.

$ clang++ -Weverything tmp/foo.cpp
tmp/foo.cpp:16:11: warning: declaration shadows a field of 'Txtbin' [-Wshadow]
    float area = 10.5;
          ^
tmp/foo.cpp:8:15: note: previous declaration is here
        float area;
              ^
tmp/foo.cpp:16:11: warning: unused variable 'area' [-Wunused-variable]
    float area = 10.5;
          ^
tmp/foo.cpp:23:14: warning: unused parameter 'argc' [-Wunused-parameter]
int main(int argc, char* argv[]){
             ^
tmp/foo.cpp:23:26: warning: unused parameter 'argv' [-Wunused-parameter]
int main(int argc, char* argv[]){
                         ^
4 warnings generated.

Instead do this, use a member initializer in the constructor.

class Txtbin{
    protected:
        float area;

    public:
        Txtbin();
        float get_area();
};

Txtbin::Txtbin()
   : area(10.5) {
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.