Home » 
        C++ Programs
    
        
    C++ program to convert speed from km/h to miles/h using class
    
    
    
    
        Learn, how can we convert speed from km/h to miles/h using the class and object approach?
        
            Submitted by Shubh Pachori, on September 04, 2022
        
    
    
    Problem statement
    Given speed in km/h, convert it into miles/h using class and object approach in C++.
Example:
Input:
Enter Speed in km/h : 432.12
Output:
Speed in miles/h : 268.507
    C++ code to convert speed from km/h to miles/h using the class and object approach
#include <iostream>
using namespace std;
// create a class
class Speed {
  // private data member
 private:
  float km_per_h;
  // public member functions
 public:
  // getSpeed() function to insert 
  // speed in km/h
  void getSpeed() {
    cout << "Enter Speed in km/h : ";
    cin >> km_per_h;
  }
  // changeSpeed() function to convert speed
  // from km/h to mile/h
  double changeSpeed() {
    // initializing float type variable to
    // store speed in mile/h
    float mile_per_h;
    // converting the speed
    mile_per_h = (km_per_h * 0.6213712);
    // returning the speed
    return mile_per_h;
  }
};
int main() {
  // create object
  Speed S;
  // float type variable to 
  // store converted speed
  float speed;
  // calling getSpeed() function to 
  // insert speed
  S.getSpeed();
  // calling changeSpeed() function to 
  // convert speed
  speed = S.changeSpeed();
  cout << "Speed in miles/h : " << speed;
  return 0;
}
Output
Enter Speed in km/h : 119.1
Speed in miles/h : 74.0053
    Explanation
    In the above code, we have created a class Speed, one float type data member km_per_h to store the speed in km/h, and public member functions getSpeed() and changeSpeed() to store speed in km/h and to convert it to miles/h.
    In the main() function, we are creating an object S of class Speed, reading the inputted speed by the user using getSpeed() function, and finally calling the changeSpeed() member function to convert it to miles/h. The changeSpeed() function contains the logic to convert the speed from km/h to miles/h and printing the result.
	C++ Class and Object Programs (Set 2) »
	
	
    
    
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement