Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A method can't access a member variable of the same class (C++)

I wrote a short program to illustrate the principles of inheritance for my school project, but I am having a weird problem. Here is my code: (I have omitted all the code that isn't the problem)

class Car
{
protected:
    double fuelLevel;
public:
    void fuelUp(double);
};

void fuelUp(double fuel)
{
    Car::fuelLevel += fuel;
}

and this is the build log:

||=== Build: Debug in wierdError (compiler: GNU GCC Compiler) ===|
||In function 'void fuelUp(double)':|
|4|error: 'double Car::fuelLevel' is protected|
|11|error: within this context|
|4|error: invalid use of non-static data member 'Car::fuelLevel'|
|11|error: from this location|
||=== Build failed: 4 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

I have no idea about what this error means and I hope there is somebody who can help me.

like image 788
Sunbart Avatar asked Jan 07 '14 20:01

Sunbart


3 Answers

That function should be written as a member of the class Car

void Car::fuelUp(double fuel)
{
    fuelLevel += fuel;
}

The way you wrote it, it does not have access to any of the member variables in Car because it is a different function than the one you declared in the class.

like image 127
Cory Kramer Avatar answered Oct 17 '22 02:10

Cory Kramer


This

void fuelUp(double fuel)
{
    Car::fuelLevel += fuel;
}

is not a method. It is some function that has the same name as the method declared inside the class. This code could work if Car::fuelLevel would be public static data member of the class.

When you define a method outside a class definition you should specify the class to which the method belongs.

void Car::fuelUp(double fuel)
{
    Car::fuelLevel += fuel;
}
like image 28
Vlad from Moscow Avatar answered Oct 17 '22 02:10

Vlad from Moscow


The way that you have it written Car::fuelLevel += fuel is triyng to access the variable fuelLevel as if it were static. You need to either make that variable static or, more likely what you meant to do, is make the method

void Car::fuelUp(double fuel)
{
    fuelLevel += fuel;
}

If it makes it any more clear why your original code was wrong, you could also change it to:

void Car::fuelUp(double fuel)
{
    this->fuelLevel += fuel;
}

Notice in the second variant that you are accessing the field via this->, which is implicitly happening in the first version. Your version had it accessing the field via the class Car::.

like image 1
FuriousGeorge Avatar answered Oct 17 '22 03:10

FuriousGeorge