Best practice for setting a lower hierarchy private field in c++

I have to following classes:

//file: A.h
class A
{
    private:
       int num;
    public:
       A(int num);
       void setNum(int num);
       int getNum();       
};

//file B.h
class B
{
    private:
       A a;
    public:
       B(int num);   
       A getA();
};

Class A is contained in class B. Class A has a private field ‘num’. Class A has a public getter and a setter for the private field ‘num’. When constructing an object in class B, it forwards the value of ‘num’ to the object A it contains.

After I create object B (and therefore also the contained object A) what is the best practice to set the value of A.num to a different value from the context of B.

For instance, this doesn’t seem to work:

// file main.cc
int main()
{ 
    B b(5);
    B.getA().setNum(7);
}

Thanks,


Source: oop

Leave a Reply