BASIC CLASS

Hey experts! Could somebody please show me step by step how to create this simple class with two attributes, Speed which is an int data type and turn time which is a double.

If anyone has code for a basic class similar to this with two attributes that includes comments it would help me a lot.

Here is what i have so far (Not a lot ! )

1
2
3
4
5
6
7
8
9
10
11
  #include <iostream>
using namespace std;
class Vehicle{
public:
	int SetSpeed; // or should this be "void SetSpeed (int Speed)"
	int SetTurnTime;}
private:
	int theSpeed;
	int theTurnTime;
	
}


As for the header file i have no idea what to put in it
Last edited on
You've created the two attributes at lines 8 and 9. However, you've said that turn time should be a double. Why have you deckared it as an int?

// or should this be "void SetSpeed (int Speed)"
Yes, this should be a function prototype. What you have at lines 5 and 6 are variable declarations, not function prototypes.

What you posted, is what should go in the header file.

Last edited on
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;
class Vehicle{
public:
	void SetSpeed (int Speed)
	void SetTurnTime (double TurnTime;} // function prototype 
private:
	int theSpeed;
	double theTurnTime;  // declare variables 
	
}


What would be my next steps in writing this program ?
It might be something like this:
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
//this is the .h file
//declarations:
class CVehicle{
public:
  void mSetSpeed(int newspeed); //method to change mTheSpeed
  void mSetTurnTime(double newturntime); // mTheTurnTime
  CVehicle(); //constructor, this is called everytime you create an
  //CVehicle object
private:
  int mTheSpeed; //private variable
  double mTheTurnTime;
};

//this is the .cpp file
//definitions:
CVehicle::CVehicle(){
//constructor
//set initial values
  mTheTurnTime = 0.0;
  mTheSpeed = 0;

}
void CVehicle::mSetSpeed(int newspeed){
  mTheSpeed = newspeed;
}

void CVehicle::mSetTurnTime(double newturntime){
  mTheTurnTime = newturntime;
}

Last edited on
Could you explain the purpose of line 7 , the constructor ?

A constructor its a method with the same name of the class, its (automatically) called everytime you create an instance of that class. Its used to do some initialization.

lets suppose your main.cpp looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "CVehicle.h" 
int main(){
 //do something...
 CVehicle OBJVehicle; //create an CVehicle object.
 //now OBJVehicle::CVehicle will be called automatically
 // then mTheSpeed = 0 and mTheTurnTime =0.0 initially

 //then:

 OBJVehicle.mSetSpeed(10); //now mTheSpeed = 10


}


Sorry for my english, its not my main language.
Last edited on
Thanks for clearing this up!

Last edited on
Ok. Send it.
Topic archived. No new replies allowed.