confusion between constructor and mutator

in my program i'm supposed to have an constructor that should accept the car’s year and make as arguments and assign these values to the object’s year and make member variables. The constructor should initialize the speed member variable to 0.

but the next step asks me to make sure i have accessors that should be created to allow values to be retrieved from an object’s year, make, and speed member variables.

when i wrote down the code, it seemed like the constructor was already doing the job of the accessor, with the exception of maybe the speed member..



here is my Car.h file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  
#ifndef CAR_H
#define CAR_H
#include <string>
using namespace std;

class Car
{
private:
	int carYear, carSpeed;
	string carMake;
public:
	Car(int, string);							  //this is the constructor
	int accelerateFunction(int);
	int brakeFUnction(int);
	~Car();
		
};
#endif 


and my class function implantation file
1
2
3
4
5
6
7
8
9
10
11
12
13
//this is the class function implementation file
#include "Car.h"
#include <string>
using namespace std;


Car::Car(int localCarYear, string localCarMake)		
{
	carYear = localCarYear;
	carMake = localCarMake;
	carSpeed = 0;

}

(i haven't written my other functions implementation, but i feel like once i resolve this problem i may have a couple of questions regarding them as well)
Last edited on
Think about this in terms of the CRUD model.
Create, Read, Update and Delete.

Create = Constructor
Read = Accessor / "Getter"
Update = Mutator / "Setter"
Delete = Destructor.

I think you are confusing your Assessor with a Mutator. No?
Last edited on
A constructor's job is to initialize the object. carYear and carSpeed do not have default values, therefore it is the responsibility of your constructor to initialize these values. Because carMake is a std::string, std::string's default constructor will be invoked initializing carMake to an empty string if you don't otherwise initialize it.

You need accessors and setters because your member variables are private. As such, if a user of your class wants to know the car's speed, it would call getSpeed().
1
2
3
int Car::getSpeed () const   // Accessor/getter
{  return carSpeed;
}

Likewise if you want to specify the car's speed, you could call setSpeed().
1
2
3
void Car::setSpeed (int newSpeed)  // Setter
{  carSpeed = newSpeed;
}

You've defined accelerateFunction and brakeFunction (double check your capitialization). These can serve as mutators which change the speed by a specified amount.
Last edited on
oh sorry, yeah i meant mutator, brain fart there.
okay, i think i'm starting to understand. thanks!
Last edited on
Topic archived. No new replies allowed.