C++: Creating an object

We will use the train as an example and create a train object with relevant method associated with the object.

Lets say we need to calculate the number of days that we need to travel between 2 cities. We would need the speed of the train and the distance between the 2 cities.

#include <iostream>
#include <string>

using namespace std;

class Train

	double speed;
	double dist;

	double Days(double, double);

	Train();  //This is the constructor
	~Train();  //This is the destructor


double Train::Days(double sp, double dist)

	double speed = sp;
	double distance = dist;

	return (dist/sp)/24;



int main()

	double speed = 10;
	double distance = 1000;

	Train Train1; // instance declaration
	cout << "No of days: " << Train1.Days(speed,distance);
	cout << endl;


In this example, there are 2 data members speed and train.  In our constructor, we did not initialize them within the constructor.  We are assuming that the values can change.

So in line 42, we declare the instance Train1 without passing in any parameters.  As a result, in our method Days, we would need to pass in the 2 parameters speed and distance.


Series Navigation<< C++: Reusing a method
C++: Work out the method first >>