[Solved] Creating a second instance of an object changes whole class behavior (C++)


WayPointStack wps = *(new WayPointStack());

must be

WayPointStack wps;

because it is enough and that removes the memory leak


In

 WPCommand WayPointStack::GetNextWP()
 {
     ...
     return *(new WPCommand(_END, 10000));
 }

you create an other memory leak, may be do not return the element but its address allowing you to return nullptr on error ?

 /*const ?*/ WPCommand * WayPointStack::GetNextWP()
 {
     Serial.println("Pointer = ");
     Serial.println(pointer);
     Serial.println("Length = ");
     Serial.println(_length);
     if (pointer < _length){
       return &_wp[pointer++];
     }
     return nullptr;
 }

else use a static var :

  WPCommand WayPointStack::GetNextWP()
  {
      ...
      static WPCommand error(_END, 10000);
      return error;
  }

In

void WayPointStack::AddWP(int target, int time)
{
    if (_length == arrSize)
        return;
    _wp[_length] = *(new WPCommand(target, time));
    _length++;
}

you create an other memory leak, you just need to initialize the entry :

 void WayPointStack::AddWP(int target, int time)
 {
     if (_length == arrSize)
         return;
     _wp[_length]._target = target, time));
     _wp[_length]._time = time;
     _length++;
 }

you do not signal the error when you cannot add a new element, what about to return a bool valuing false on error and true when you can add :

 bool WayPointStack::AddWP(int target, int time)
 {
     if (_length == arrSize)
         return false;
     _wp[_length]._target = target;
     _wp[_length]._time = time;
     _length++;
     return true;
 }

Finally Why do you not use a std::vector for _wp

1

solved Creating a second instance of an object changes whole class behavior (C++)