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.
The way that you have it written
Car::fuelLevel += fuel
is triyng to access the variable fuelLevel as if it werestatic
. You need to either make that variablestatic
or, more likely what you meant to do, is make the methodIf it makes it any more clear why your original code was wrong, you could also change it to:
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 classCar::
.This
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.
That function should be written as a member of the class
Car
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.You must refer your function to a certain class when defining it outside the class. So you should write the
Car
before defining the function. It must be on the formvoid car::fuelUp(double fuel)