0

Why am I getting no output?

#include <iostream> using namespace std; class Car{ private: int horsepowers; public: void setHorsepowers(int x) { x = horsepowers; if(horsepowers>800){ cout<<"Too much"<<endl; } } int getHorsepowers() { return horsepowers; } }; int main() { int horsepowers; cin >> horsepowers; Car car; car.setHorsepowers(horsepowers); cout << car.getHorsepowers(); return 0; }

22nd Nov 2021, 5:36 PM
Rubayet Kamal
Rubayet Kamal - avatar
6 Respostas
+ 2
Yes, that's right. You are calling the setter function with the VALUE in the x variable. And then this VALUE will be stored in horsepowers: Variable <- Value horsepowers = x
22nd Nov 2021, 10:27 PM
Coding Cat
Coding Cat - avatar
+ 4
😮 Hmm, that's lesson one for variables. This is a normal value assigment to a variable. This works only in one direction: Variable <- new value If both directions should be possible, how do the compiler should know, what direction do you want in this case? Maybe you can look at it like this: FIRST open a container, THEN put in the items.
22nd Nov 2021, 7:52 PM
Coding Cat
Coding Cat - avatar
+ 3
void setHorsepowers(int x) { horsepowers = x;
22nd Nov 2021, 5:55 PM
SoloProg
SoloProg - avatar
+ 1
Use: horsepowers = x; instead of x = horsepowers; void setHorsepowers(int x) { horsepowers = x; if(horsepowers>800){
22nd Nov 2021, 5:56 PM
Coding Cat
Coding Cat - avatar
+ 1
SoloProg Coding Cat mind telling the difference between horsepowers = x and x = horsepowers? Really curious on how the compiler understands one and not the other.
22nd Nov 2021, 6:45 PM
Rubayet Kamal
Rubayet Kamal - avatar
+ 1
So in this case Variable is horsepowers and the parameter is X which is going to be the argument when called later by the function, am I right? I was first confused because both aren't numbers,hence both are variables. Guess I was wrong there.
22nd Nov 2021, 10:14 PM
Rubayet Kamal
Rubayet Kamal - avatar