I have two classes, foo and bar, where bar contains a pointer to foo, as below.
#include<iostream>
#include<memory>
class foo {
private:
int num{4};
public:
void sum(const int& to_add) {num += to_add;}
int access_num() {return num;}
};
class bar {
private:
std::shared_ptr<foo> ptr;
public:
void change_ptr(foo& f) {
auto new_ptr = std::make_shared<foo>(f);
ptr = std::move(new_ptr);
}
std::shared_ptr<foo> access_ptr() { return ptr; }
};
If I want to execute the member function sum() of foo via the pointer in bar, how do I do it?
Currently, trying
foo f;
std::shared_ptr<bar> bar_ptr = std::make_shared<bar>();
bar_ptr->change_ptr(f);
// Add three to the int stored in f via the pointer
bar_ptr->access_ptr()->sum(3);
std::cout << f.access_num() << std::endl;
does not work, outputting 4.