the setter is working well but, why the getter is return null like the object (app[0]) is reinstance?
You are having a problem because you are returning a temporary copy of your Car
member variable rather than a reference to the member variable itself. More specifically, your member function getCar()
returns Car
rather than Car&
. Your current version will copy the value of the member variable car
into a temporary and return the temporary as its return value, not the member variable itself. So then in this code:
app[0].getCar().setColor("red");
You are actually modifying the contents of the temporary copy that getCar()
returned. Since this is a temporary copy, the temporary will be destroyed at the end of the statement, and all your modifications will be lost. Moreover, the car
member variable of app[0]
will continue to have its default value.
What you want is to return a reference to the member variable itself that will allow you to edit its contents directly. To do this, you need to modify your App
class in the following way:
class App(){
private:
Car car;
public:
App():car(){
}
Car& getCar(){
return car;
}
}
Now getCar()
returns a reference to the member variable car
, and modifying this reference will directly modify the car
member variable of app[0]
, giving you your expected behavior.