Home > other >  How to propagate changes from one class to another in C ?
How to propagate changes from one class to another in C ?

Time:03-09

Having this code:

#include <iostream>
#include <vector>
#include <string>

class A{
public:
    A(std::string const& name) : name(name) {}
    std::string const& getName() const {
        return name;
    }
private:
    std::string name;
};

class B{
public:
    void add(A const& a){
        //vec.emplace_back(a) does not help either
        vec.push_back(a);
    }
    std::vector<A> const& getVec() const {
        return vec;
    }
private:
    std::vector<A> vec;
};

class C{
public:
    C(B const& b, A const& a) : a(a), b(b) {}
    A const& getA() const {
        return a;
    }
    B& getB() {
        return b;
    }

private:
    A a;
    B b;
};

class D{
public:
    C& add(C& c){
        A const& a = c.getA();
        B& b = c.getB();

        b.add(a);
        vec.push_back(c);
        return c;
    }
private:
    std::vector<C> vec;
};

int main(){
    A a1{"first"};
    A a2{"second"};

    B b;

    C c1{b, a1};
    C c2{b, a2};

    D d;
    d.add(c1);
    d.add(c2);

    for(A const& a : b.getVec()){
        std::cout << a.getName() << ' ';
    }
}

There is no output from the program, but

I would expect output:

first second

Where the B class is holding the vector, and D is trying to modify it (c.getB().add()) via class C. It's just simple example (encountered in a school project), but I wanted to know by this example the flow of changes between classes.

CodePudding user response:

C's members are not reference types. Both c1 and c2 are storing copies of the constructor arguments.

So

d.add(c1);
d.add(c2);

doesn't affect b in main, only the members of c1 and c2, which are copies of the original b, a1 and a2 in main.

  • Related