access a member data/function from a function of an object instantiated in target scope

How can C++ access all public member data/functions from within a function of an object instantiated in the same scope of that access target?

illustrated such

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
struct K {
	
	void fn_K() {
		
		cout<< "x is "<<x<<"\n";
		fn_L();
	}
};

class L {
	
	int x=9;
	void fn_L() {
		int y=5;
		cout<< "y is "<<y<<"\n";		
	}
	
	K k;
};


int main(){

	k.fn_K();

}
Last edited on
Explicate!
Show some example code.
Use code tags.
Last edited on
abdulbadii wrote:
access a member data/function from a function of an object instantiated in target scope

You will have to come up with a better translation of that in English.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;

class L
{
public:
	int x = 9;
	void fn_L()
	{
		int y = 5;
		cout << "y is " << y << '\n';		
	}
};

struct K
{
	void fn_K( L ell )
	{
		cout<< "x is "<< ell.x << '\n';
		ell.fn_L();
	}
};

int main(){
	K kay;
	L ell;
	kay.fn_K( ell );
}
At first sight, it seems a classic circular dependency problem.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>


struct K;


class L {
public:
    explicit L(K* const);

    void fn_L() const;
    int getX() const;

private:
    K* k;
    int x { 13 };
};


struct K {
    L* l { nullptr };
    int y { 666 };
    void fn_K() const;
};


void K::fn_K() const
{
    std::cout << "x is " << l->getX() << '\n';
    l->fn_L();
}


L::L(K* const k_arg)
    : k { k_arg }
{
}


void L::fn_L() const
{
    std::cout << "y is " << k->y << '\n';
}


int L::getX() const { return x; }


int main()
{
    K k;
    L l { &k };
    k.l = &l;
    k.fn_K();
}


Output:
x is 13
y is 666

Please, add details to get better answers.
Topic archived. No new replies allowed.