Concatenating Classes with Map

I'm having trouble with the following code:
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>

#include <map>
using namespace std;
class a{
	private:
		int id;
	public:
		a(){}
		a(int id_){
			id=id_;
		}
		void setId(int i){
			id=i;
		}
		int getId(){
			return id;
		}
};
class b{
	private:
		map <int,a> _b;
		int id;
		int _counterId;
	public:
		b(){}
		b(int id_){
			id=id_;
			_counterId=0;
		}
		void setId(int i){
			id=i;
		}
		int getId(){
			return id;
		}
		void create_a (int id){
			a a1 (id);
			_b[_counterId]=a1;
			cout<<"Counter Id "<<_counterId<<endl; 
			_counterId++;
			
		}
		a geta(int id){
			return _b[id];
		}
		int getSize(){
			return _b.size();
		}
};
class c{
	map <int,b> _c;
		int id;
		int _counterId;
	public:
		c(){}
		c(int id_){
			id=id_;
			_counterId=0;
		}
		void setId(int i){
			id=i;
		}
		int getId(){
			return id;
		}
		void create_b (int id){
			b b1 (id);
			_c[_counterId]=b1; 
			_counterId++;
			
		}
		b getb(int id){
			return _c[id];
		}
};

int main(){
	c c1 (1);
	cout<<c1.getId()<<endl;
	c1.create_b(2);
	cout<<c1.getb(0).getId()<<endl;
	c1.getb(0).create_a(3);
	cout<<c1.getb(0).getSize()<<endl;
	cout<<c1.getb(0).geta(0).getId()<<endl;

	}


The first and second cout of main works fine, but the other two don't. It's like when I create an a and put it in _b it disappears.
What I am doing wrong?
Thanks for the help.
getb is returning a copy.

1
2
3
4
5
6
7
8
// this line creates an unnamed temporary b object, creates an a in it, then throws the b away
c1.getb(0).create_a(3);

// similar to this:
{
  b temporary = c1.getb(0);
  temporary.create_a(3);
} // <- 'temporary' dies here 


So note that you're modifying the temporary object and not the actual b contained within the c1 object. c1's b object remains unaltered.


If you want to do this, you'd need to return a reference, rather than a copy:

1
2
3
  b& getb(int id){  // <- return a 'b&', not a 'b'
    return _c[id];
  }
Last edited on
It worked.
Thanks for the help, i appreciate it.
Topic archived. No new replies allowed.