#include <iostream>
#include <map>
usingnamespace 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.
// 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];
}