0

Can anyone explain me why does this happened?

When I call member function printEvent() inside the block of if-else,I get the correct output,but when I call printEvent() after the block I get this unknown result.

        list<Event*> currentEvents;
    for (j=1; j <= eventsNum; ++j)
    {   
        Event * newEvent;

        if (isIndividual(inFile)) {
            IndividualEvent newIndi = returnIndi(inFile);
            newEvent = &(newIndi);
            newEvent->printEvent();
        }else {
            TeamEvent newTeam = returnTeam(inFile);
            newEvent = &(newTeam);
            newEvent->printEvent();
        }
        cout << "WHY?" << endl;
        newEvent->printEvent();


        currentEvents.push_back(newEvent);
    }
    TVNode.push_back(newEmission);
}

OUTPUT

<Filiko1>
WHY HERE?
<Filiko1q<15-06-2015,14:00<Athens<0`W                                             ����Athensq<Football<1<0>!0����Footballq<2q<Olympiakos<PSG!
                                                                     ����OlympiakosxW^��DW����PSG^��DWPW�^��DWi�n

The above code is part of a big exercise!

Nikolas
  • 161
  • 1
  • 12
  • 3
    After leaving the if clause scope `newEvent` points to an object that was on the stack and has been destroyed. – Jonathan Potter Jun 15 '15 at 23:12
  • Is there any way to solve this problem ? Thanks for your time:) – Nikolas Jun 15 '15 at 23:13
  • 1
    If you're storing derived objects of different types in a list you should use `list>` and then add then to the list like `currentEvents.push_back(unique_ptr(new IndividualEvent(returnIndi(inFile))));` etc. – Jonathan Potter Jun 15 '15 at 23:16
  • Do you really, really need to have a vector of pointers? This is really asking for trouble. – David Schwartz Jun 16 '15 at 00:10
  • I use a list of pointer because I want to store multiple derived classes types into the same list.Is there any safer way to do it ? – Nikolas Jun 16 '15 at 11:08

1 Answers1

1

The newEvent after if or else block points to already destructed object, as the object's lifetime is limited by the scope in which it is defined. In your case objects newIndi and newTeam will be destroyed after if-else statement, while newEvent pointer still points at one of them.

See this link to learn about C++ scopes: http://en.cppreference.com/w/cpp/language/scope

Oleg Andriyanov
  • 5,069
  • 1
  • 22
  • 36