- 1

encapsulation c++ help

Hi, can somebody correct my code? #include <iostream> using namespace std; //class definition class Car{ //private area private: int horsepowers; //public area public: //complete the setter function void setHorsepowers(int horsepowers) { if (horsepowers > 800){ cout << "Too much"<<endl; cout << horsepowers << endl; } else { cout << horsepowers; } } //complete the getter function int getHorsepowers() { return horsepowers; } }; int main() { //getting input int horsepowers; cin >> horsepowers; //creating the object of class Car Car car; //setting the value for private member car.setHorsepowers(horsepowers); //printing the value of private member cout << car.getHorsepowers(); return 0; } THE ACTUAL PROBLEM: You are a supercar engineer and currently setting the engine's horsepower. Complete the given program by completing methods to set and get the horsepower of the car object in order to output it. The program should warn "Too much" if the inputted horsepower is above 800. Sample Input 950 Sample Output Too much 950 DEFAULT CODE: #include <iostream> using namespace std; //class definition class Car{ //private area private: int horsepowers; //public area public: //complete the setter function void setHorsepowers() { } //complete the getter function int getHorsepowers() { } }; int main() { //getting input int horsepowers; cin >> horsepowers; //creating the object of class Car Car car; //setting the value for private member car.setHorsepowers(horsepowers); //printing the value of private member cout << car.getHorsepowers();

6th Aug 2021, 12:20 PM
vilrau12
vilrau12 - avatar
2 Respostas
+ 1
Setter function should be: void setHorsepowers(horsepowers) { this->horsepowers = horsepowers; } Getter function should be: int getHorsepowers() { return horsepowers; } In main function you should write if statement: if (car.getHorsepowers() > 800) { cout << "Too much" << endl; } cout << car.getHorsepowers() << endl;
6th Aug 2021, 12:31 PM
Roma Butaku
Roma Butaku - avatar
0
Getter functions are used to return private attributes (horsepowers) inside the class (Car).So, you should just simply return horsepowers inside it. int getHorsepowers(int h){ return horsepowers;} The setter function is a void function . It doesn't return anything. You can print here whatever you want. So, you should print the warning and the value of horsepowers with a simple condition using if & else. void setHorsepowers(){ if(h>800){ cout<<"Too much"<<endl; //this will always be printed whenever you call the setter function & the condition is met. h=horsepowers;} // this is returned by getter function. else{horsepowers=h;} //just return the value with no warning. Remaining code remains the same.
10th Jan 2024, 7:37 AM
Tarikul Tuhin
Tarikul Tuhin - avatar