hi i have faced an issue while accessing an object,
in my program there are 2 classes class A and B
class b has a member variable name, which kepts as private.and gettes/setter functions to access this variable(bcoz the variable is private).
in Class A, has a member variable , object of class B b(private).And i have used a getter to get this object outside the class.
now i want to set the name of object b using the object of class a.
so created the following code, but i didnot working.
please help me to solve this.
// GetObject.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
class B
{
int name;
public:
int getname()
{
return name;
}
void SetName(int i)
{
name = i;
}
};
class A
{
private:
B b;
public:
B GetB()
{
return b;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int ii = 10;
A a;
a.GetB().SetName(ii);
std::cout<<" Value :"<<a.GetB().getname();
getchar();
return 0;
}
You need to return the member by reference (or pointer):
The way you have it now, you’re returning a copy of the object.
So
B A::GetB()doesn’t return the original object. Any changes you make on it will not affect the member ofa. If your return by reference, a copy is not created. You would be returning the exactBobject that is a member ofa.