In this sample program:
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
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;
}