user13676
user13676

Reputation: 119

associations between 3 classes

I have 2 classes A,B as below:

class A{
public:
   int size;
   A(int s){size=s;}
};

class B{
B(int d):A(d){}
};

I need to know how I can define another class, class C, so class B can update the size (or any values) in class A, but class C can access the updated value in class A.

Upvotes: 1

Views: 52

Answers (2)

erol yeniaras
erol yeniaras

Reputation: 3797

I hope I understood it correctly but it seems to me that you can inherit C from A, so that you can access its data as it is updated. Or you can create a data member of C of type class A, and implement getter in A and call from C whenever necessary. For example:

class C {
private:
    A a;
public:
    void foo() {
        a.getSize();
    }
}

Hope that helps!

Upvotes: 1

ANjaNA
ANjaNA

Reputation: 1426

simple, Write another class class C that inherits from class B. so, class B can access the class A data members as well. you can use public/protected or private inheritance. But class B:class A should only be public/protected.

Then Write set methods in class B(so class B can update the size) and get methods in class C(class C can access the updated value in class A).

You should create a pointer and type case accordingly.

OR

You can use singleton pattern to maintain a single object(instance). It depend on the your requirement.

Upvotes: 0

Related Questions