clarkk
clarkk

Reputation: 27685

class with float variable

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;
}

Upvotes: 0

Views: 61

Answers (2)

Vaughn Cato
Vaughn Cato

Reputation: 64308

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();
};

Upvotes: 5

Brian Cain
Brian Cain

Reputation: 14619

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) {
}

Upvotes: 0

Related Questions