+ 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
10 odpowiedzi
+ 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();
}
}
+ 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.
+ 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.
+ 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.
+ 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