Function for returning total weigth of a train

How can I override a function to return the total weigth of a train??


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class TrainRoute
{
....
int totalWeight()
	{

		return 100;
	}
}

class FreightTrainRoute : public TrainRoute
{
protected:
	int nbOfWagons;
	float* weigthPerWagon;

....

//this function to be orrided
int totalWeight()
{

}





Last edited on
To override a function, you have to declare it virtual in the base class.

Why is weigthPerWagon a pointer?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class TrainRoute
{
//    ....
    virtual int totalWeight()
//  ^^^^^^^
    {   return 100;
    }
};

class FreightTrainRoute : public TrainRoute
{
protected:
    int nbOfWagons;
    float* weigthPerWagon;
//    ....

        //this function to be overriden
    int totalWeight()
    {   return nbOfWagons * (*weigthPerWagon);
    }
};


PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Topic archived. No new replies allowed.