Seems you're rather new at this so I'll try to see if I can explain. The fixed code that would work would look like this:
#include <iostream>
using namespace std;
class Foo {
public:
int a;
};
class Bar: public Foo {
public:
int b;
};
Foo *changeA(Foo *f) {
f->a = 6;
return f;
}
int main() {
Bar *b = new Bar();
changeA(b);
cout << b->a << endl;
return 0;
}
The problem with what you were doing was that when you pass b into that function, it passes a copy of it. Whereas you want to modify the original object itself. To elaborate on this, a copy of b is created and passed into that function, that function modifies it and returns it. so if you were to do a
Foo a = changeA(b);
That a would have the modified value that you want. but the original object would be left unchanged.
When you pass it as a pointer, the changes you will make within the changeA function will be applied to the original b as well. This same thing can also be achieved by using a reference (&), and It would be a lot easier:
#include <iostream>
using namespace std;
class Foo {
public:
int a;
};
class Bar: public Foo {
public:
int b;
};
Foo changeA(Foo &f) {
f.a = 6;
return f;
}
int main() {
Bar b;
changeA(b);
cout << b.a << endl;
return 0;
}
Here, You literally make one change and it will work, what the ampersand does is ensure that the you don't create a copy and pass that into the function, and pass the object itself instead. So this way, all changes are made to the original object itself.