+ 2

How do i call methods within a function outside the class?

I've recently learnt about some of the Foundations of oop, and right now I'm trying to create a class which has cars as objects, and allows you to change to colour and add a spoiler. right now I'm making a function outside the class which let's you pick whether to add spoilers or change the colour. my only problem is: I'm not sure how to call the methods within this function. https://code.sololearn.com/c4NRq5yoPkPr/?ref=app

30th Jul 2017, 1:50 PM
X-1
X-1 - avatar
10 Réponses
+ 8
This is how I have modified your code for edit_car function: void edit_car(car &obj); int main() { car lambo; lambo.car_colour = "yellow"; lambo.doors = 2; lambo.wheels = 4; cout << "lamborghini:" << endl; lambo.show_wheels(); gap(); lambo.show_car_colour(); gap(); lambo.show_doors(); gap(); edit_car(lambo); return 0; } void edit_car(car &obj){ string option; cout << "options \n add spoiler \n change colour \n what would you like to do?" << endl; cin >> option; if(option == "add spoiler"){ obj.add_spoiler(); gap(); } if(option == "change colour"){ obj.change_colour(); gap(); } }
30th Jul 2017, 2:42 PM
Hatsy Rei
Hatsy Rei - avatar
+ 8
@Immortal You shouldn't be creating a new instance of a car. The spoiler and colour method should be called using the original instance of the car created in main(). You will want to pass your car object into the function.
30th Jul 2017, 2:44 PM
Hatsy Rei
Hatsy Rei - avatar
+ 8
@Immortal The lambo inside the global function will call it's own method, and then call its destructor once the function ends. The lambo inside main will be unaffected.
30th Jul 2017, 3:22 PM
Hatsy Rei
Hatsy Rei - avatar
+ 7
@Immortal Yes, it is working, but the attribute would be added to c instance, instead of lambo, which was the original intention of the program.
30th Jul 2017, 2:46 PM
Hatsy Rei
Hatsy Rei - avatar
+ 1
@Hatsy Rei I've done that, and the program will run. only problem now is that the methods are not being run where nessecary
31st Jul 2017, 10:01 AM
X-1
X-1 - avatar