tags:

views:

131

answers:

5
  using namespace std;

  class A {
      public:
         A() {}
         ~A() {}

         map<int, string*>& getMap() {
             return mapStr;
         }

         void setMap(const map<int,string*> m) {
             mapStr = m;
         }

      private:
          map <int, string*> mapStr;
  };


  class B {

      public:
      A getA() {
          return a;
      }
      private:
      A a;

  };

  int main(int argc, char*argv[]) {

      map<int, string*> mm;
      mm.insert(std::make_pair(1, new string("abc")));
      mm.insert(std::make_pair(2, new string("def")));

      B b;
      b.getA().setMap(mm);
      cout << "Size " << b.getA().getMap().size() << std::endl;
      return 0;
  }

Output: Size 0

Any ideas as to why does this return the map size to be 0 and what needs to be done to be fixed

+14  A: 

Your getA method is returning a temporary copy of a, so your call to setMap is modifying that copy, not the original. One way to fix this would be to have getA return a reference or pointer to a

Laurence Gonsalves
A: 

Each call to getA() is creating and returning a new temporary object.

So the first call:

b.getA().setMap(mm);

Creates an A object adds mm into it.
This then goes out of scope and destroys the map.

This line:

cout << "Size " << b.getA().getMap().size() << std::endl;

Creates a completely new A object with its own empty map.
As it is a new object the size of the map is zero.
Once this goes out of scope it is again destroyed.

I think what you meant to do is:

class B
{ 
    A& getA()         // Notice the & just after the A 
    {                 // rather than return an object by value
        return a;     // you want to return a reference to the object inside
    }                 // your B object.
    private:
        A a;  
}
Martin York
A: 

You're returning a copy of an A, not the A object you're modifying. Try out this code to understand the difference:

int main (int argc, char* argv[])
{
  map<int, string*> mm;
  mm.insert(std::make_pair(1, new string("abc")));
  mm.insert(std::make_pair(2, new string("def")));

  B b;
  A a = b.getA();
  B bb;
  bb.getA().setMap(mm);
  a.setMap(mm);

  cout << "A Size " << a.getMap().size() << std::endl;
  cout << "BA Size " << bb.getA().getMap().size() << std::endl;
}
Matt
A: 

B::getA() is returning an object by value. Si when you call A::setMap() you are setting the map of the temporary object.

Change the signature of getA() to:

A &getA();
R Samuel Klatchko
A: 

Your method getA currently returns a copy, instead of a reference to, the a member. Instead, you want to return A& from getA. This will allow you to return a reference to your member variable instead of a copy of it.

Justin Voskuhl