Hi all, I am struggling with classes and constructors. I have no clue if I am even on the right track with this. I included the task and my attempted and unfinished code below. I'd really appreciate any advice or references to help me understand and complete the task. -Thanks
TASK:
Write a class named Car with member variables:
* yearModel, Make, Speed
* use a Constructor that accepts s year model and make as arguments. It should also assign 0 to the speed
*use accessors
* accelerate and brake functions that add and subtract 5 from speed each time it is called.
*Demonstrate the class in a program that creates a Car object, and then calls the accelerate function 5 times. After each call to the accelerate function, get the current speed of the car and display it. Then, call the brake function ve times. After each call to the brake function, get the current speed of the car and display it.
#include <iostream>
#include <string>
usingnamespace std;
//CAR CLASS
class CAR
{
private:
//variables
int yearModel;
string make;
int speed;
public:
//constructor
CAR(int y, string m, int s);
//set variable
void setyearModel(int y){y=yearModel;}
void setmake(string m){m=make;}
void setspeed(int s ){s=speed;}
//get variable
int getyearModel(){return yearModel;}
string getmake(){return make;}
int getspeed(){return speed;}
};
int main()
{
CAR meinauto;
string automake;
int autoyear;
cout<<"Enter the make of the car."<<endl;
cin>>automake;
cout<<"Enter year of model."<<endl;
cin>>autoyear;
meinauto.setmake(automake);
meinauto.setyearModel(autoyear);
system("pause");
return 0;
}
* accelerate and brake functions that add and subtract 5 from speed each time it is called.
*Demonstrate the class in a program that creates a Car object, and then calls the accelerate function 5 times. After each call to the accelerate function, get the current speed of the car and display it. Then, call the brake function ve times. After each call to the brake function, get the current speed of the car and display it.
?
I think it's not much hard to understand an do it.
Your given task is really hard for me to understand, not clear at all.
I think constructor should be something like this,
1 2 3 4 5 6
CAR(int Year, string model, string make,int s=0){
Year = year;
Model = model;
Make = make;
speed = s;
}
I'm still working on the first part of the task to create the constructor and have a user input the year and make of the car. I am unsure how to call the constructor in the main function and how to input the user input.
I have not gotten as far as creating the accelerator and brake functions but i think it might look something like this
constructor is called automatically when you create an instant from class. CAR meinauto; will call /*notype*/ CAR(){} by auto.
In my last example,in main, I will create instant by something like, CAR meinauto(1995,"Top","mamamama",99);
And all vars in the instant will be assigned by my constructor.