thetux4
thetux4

Reputation: 1633

Nested Classes in c++

class A{
public:
      template<typename Obj>
      class MyVec{
           //some methods...
      };
      MyVec<A> a; //-> doesnt work
      //vector<A> a; //using stl vector-> this works
};

class B{
public:
      void someMethod();
private:
      A::MyVec<A> b;
};

In the method, when I do sth like:

void someMethod(){
     //...
     b[0].a.pushback(element);
     //...
}

In class A if i use std::vector everything works properly. But when i use nested class it doesn't work.

Upvotes: 1

Views: 341

Answers (2)

Michael Anderson
Michael Anderson

Reputation: 73470

I've taken your code and modified it as minimally as possible to get something that compiles. This seems to work fine. And so the error is not in the code you have shown us.

#include <iostream>
#include <string>

class A
{
  public:
    template<typename Obj>
      class MyVec{
        public:
        //My pushback just stores the value away for later.
        void pushback(Obj & o )
        {
          if( obj )
          {
            *obj = o;
          }
          else
          {
            obj = new Obj(o);
          }
          std::cout<<this<<" : Pushing object "<<&o<<std::endl;
        }

        //some methods...
        //My operator[] just returns the stored object.
        Obj& operator[](int i) { return *obj; }
        Obj * obj;
        MyVec() : obj( NULL ) {}
      };
    MyVec<A> a;
};


class B
{
public:
B()
{
   A an_a;
   b.pushback(an_a); //Better store one away since we access it in someMethod.
}
void someMethod()
{
     //...
     A element;
     b[0].a.pushback(element);
     //...
}
private:
      A::MyVec<A> b;
};

int main()
{
   //Test that it all works
   B outer;
   outer.someMethod();
}

When I run this I get:

0xbffffa5c : Pushing object 0xbffffa0c
0x3ec3c0 : Pushing object 0xbffffa2c

Which is what I'd expect. (one push in the constructor of B and one push to the internal object from someThing)

You can view the result here: http://ideone.com/BX8ZQ

Upvotes: 2

Pedro Romano
Pedro Romano

Reputation: 21

You really should show the code inside MyVec. As a first guess, maybe MyVec's operator[] isn't returning a reference, so when you do b[0].pushback you're changing a copy instead of what you want; you wouldn't get that problem if you just tested with b.pushback()...

Upvotes: 2

Related Questions