Home Segments Index Top Previous Next

181: Mainline

Now suppose that you want to initialize the radius and length member variables when you declare certain tank_car objects. The first thing you need to do is to define a constructor with two parameters:

class tank_car {
  public:
    double radius, length;
    // Default constructor:
    tank_car ( ) {radius = 3.5; length = 40.0;}
    // Constructor with two parameters:                      
    tank_car (double r, double l) {radius = r; length = l;}  
    // Volume function: 
    double volume ( ) {return pi * radius * radius * length;} 
}; 

Note that the constructor with two parameters, like the default constructor, is named for the class in which it appears. Also, there is no return data type.