Suggestion regarding an error

I have a user defined class which has a private variable x. x is a vector of a user defined struct. In the constructor of the class i am executing a statement like the following
x.push_back(y)

The gnu debugger exits at this push back statement giving an out of range error. Does anybody have an idea why am i getting this error while adding to the vector from the constructor of the class ?
Can you give an example demonstrating your problem?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class C
{
    C() ;
    ~C() ;
}

//A.h file
class A
{
  public:
    A() ;
   ~A() ;

  private:
    std::vector<C> cc ;
}

//A.cpp file
A::A()
{
    C * obj = new C() ;
    cc.push_back(*obj) ;
}


I have just given a brief of the implementation. The push_back statement is throwing an exception. x that i had mentioned earlier is basically C in this example. It is another user defined class. In case you find any difficulty let me know . i am getting the below error


(gdb) n
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check
The code you posted doesn't really demonstrate the problem because it doesn't give the error you was talking about (it doesn't even compile).

I found a memory leak in the code
1
2
    C * obj = new C() ;
    cc.push_back(*obj) ;

You are not deleting the object you created with new so you have a memory leak. It's not what causes the runtime error though. Why use new at all here?
cc.push_back(C()) ;
Last edited on
Yes Peter u were right that this code is not compilable. The actual code which was giving error would be big so i tried to write something similar to it.

However your last alternative suggestion has helped me to overcome the error i was facing of out of range. I was thinking that both do the same thing .. only difference being that the new keyword is assigning memory for the object dynamically on the heap.
Thanks Peter for the help.
Topic archived. No new replies allowed.