Changing the value of a member variable.
Sep 7, 2011 at 11:18pm UTC
The instructions that I'm provided direct me to set the speed member variable as 0 within the constructor. If that is the case, how can I change that value from 0 to anything else within my calcAccel function? Basically I want to add five to the speed every time the calcAccel function is called.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#include <string>
using namespace std;
class Car
{
private :
int yearModel;
int speed;
string make;
public :
Car (int ,string);
void setYearModel(int );
void setMake(string);
void setSpeed(int );
int getYearModel() const ;
int getSpeed() const ;
string getMake() const ;
int calcAccel() const ;
int calcBrake() const ;
};
Car::Car(int year,string mak)
{
yearModel = year;
speed = 0;
make = mak;
}
void Car::setYearModel(int year)
{
yearModel = year;
}
void Car::setMake(string mak)
{
make = mak;
}
void Car::setSpeed(int x)
{
speed = x;
}
int Car::getYearModel() const
{
return yearModel;
}
int Car::getSpeed() const
{
return speed;
}
string Car::getMake() const
{
return make;
}
int Car::calcAccel() const
{
return speed+=5;
}
int Car::calcBrake() const
{
return speed - 5;
}
Sep 8, 2011 at 12:28am UTC
The constructor sets the value only the one time when the object is created. So if you have a function that modifies the value, it will change from 0.
Sep 8, 2011 at 12:52am UTC
If you want to modify a member variable then you can not make the function const.
1 2 3
int calcAccel() const ; // this can not modify member variables
int calcAccel(); // this can
Sep 8, 2011 at 1:41am UTC
Such a simple solution solved everything, thanks!
Topic archived. No new replies allowed.