Object as a member variable

Hi, I ran into a problem while accessing an object,

in my program there are 2 classes of class A and B

class b has the name of a member variable that stores private.and gettes / setter functions for accessing this variable (bcoz - the variable is private).

in class A, has a member variable, an object of class B b (private). And I used getter to get this object outside the class.

now I want to set the name of object b using an object of class a. so I created the following code, but I didnot work.

please help me 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; } 
+4
source share
1 answer

You need to return the element by reference (or pointer):

 B& GetB() { return b; } //or B* GetB() //i'd prefer return by reference { return &b; } 

Now you have this, you are returning a copy of the object.

So BA::GetB() does not return the original object. Any changes you make will not affect Member a . If you return by reference, a copy is not created. You return the exact object B , which is a member of a .

+2
source

Source: https://habr.com/ru/post/1398962/


All Articles