0

What is the best practice to implement following scenario:
Class A holds a member object of Type B.

class A
{
private:
  B b;
};

class B
{
private:
  int x;
};

A print function which gets an object of type A as const & parameter, should print the members of aand b :

void Print(const A& a)
{
  cout << a.b.x;
}

A read function should set the values of a (and b) and their members:

void Read(A& a)
{ 
  // ...
  a.b.x = 2;
}

How should class A be implement regarding its member access?

  • Should "b" be public?
  • Should "class A" provide 2 getters for b (1 for write and 1 read access to "b")?

Additional information:
In my real system the classes A and B are much larger and they are part of a huge legacy system. In this legacy system Print and Read are member functions of a "View-Model", where Print writes the values to the GUI and Read reads the values from the GUI and sets the members of A and B. So the resposibility of A and B is to hold the data (some kind of data models).

JosefM
  • 37
  • 4
  • 2
    Why not shift the responsibility of reading and writing to `B`, or another overloads of `Print` and `Read` in this case? Still, you need to make those functions member or `friend`. – LogicStuff Jan 22 '18 at 11:38
  • 1
    I especially like how the `Read` function actually writes. Keep them guessing and on their toes. – bolov Jan 22 '18 at 11:40

1 Answers1

4

You ought to use member functions instead, and keep the data as encapsulated as possible. To that end, Print could be a member function of A:

class A
{
    B b;
public:
    void Print() const /*Let's add some const correctness*/
    {
        b.Print();
    }
};

and

class B
{
    int x;
public:
    void Print() const
    {
        std::cout << x;
    }

    B& operator=(int new_x) /*Standard form of the assignment operator*/
    {
        x = new_x;
        return *this;
    }
};

Note that I've provided an assigment operator for B. You could then build a function in class A:

void setX(int x)
{
    b = x;
}

Finally though, for your printing, the idiomatic way is to overload << for std::ostream. Then you can remove your Print functions. See How to properly overload the << operator for an ostream?.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483