Search code examples
c++oopcomposition

Can't change data members' values of member object


In this sample program:

  • I created a class A with a object member of class B
  • Class B contains data member x with a setter and a getter
  • Constructor of Class B initialize data member x with the value 5
  • Class A contains member function func () to set the value of data member x of class B to value: 7

Now the value of x before and after calling func() doesn't change to 7, what is the problem?

Here is my code:

Class A header

#ifndef A_H
#define A_H
#include "B.h"

class A
{
public:
    B getB();
    void func ();

private:
    B obj;
};

#endif // A_H

Class A implementation

#include "A.h"

B A :: getB ()
{
    return obj;
}

void A :: func ()
{
    getB().setX (7);
}

Class B header

#ifndef B_H
#define B_H


class B
{
public:
    B ();
    int getX ();
    void setX (int);
private:
    int x;


};

#endif // B_H

Class B implementation

#include "B.h"

B :: B () : x(5)
{

}
void B :: setX (int x)
{
    this->x = x;
}
int B :: getX()
{
    return x;
}

main.cpp

#include <iostream>
#include "A.h"
#include "B.h"
using namespace std;
int main()
{
    A instanceA;
    cout << instanceA.getB().getX() << "\n";
    instanceA.func();
    cout << instanceA.getB().getX();
    return 0;
}

Output:

5

5


Solution

  • This is returning by value (a copy of obj and not obj itself):

    B getB()
    {
        return obj;
    }
    

    To return the variable itself, you should return a reference to it:

    B& getB()
    {
        return obj;
    }