Difference between Objects and Object Pointers

What’s the difference between doing,

EventList temp;

EventList* temp = new EventList();

Where now temp you access it’s vars by doing using . and the other is ->

Besides that difference, what else? Pointer allocates on the heap while just EventList is on the stack. So is it primarily a scope thing?

Eventlist temp is allocated and deallocated automatically within the scope in which it is called. That is, when you run the following code:

{
    EventList temp;
}

The default constructor for EventList is called at the point of its declaration, and the destructor is called at the end of the block.

EventList *temp = new EventList(); is allocated on the heap. You can read more about it here.

There is short summary

Object on the stack EventList temp;

  • access is little bit faster, there is no derefferencing
  • object are automatically deleted at the end of method which creates them so we don’t have to care about their deletion
  • stack size is limited ( much more than heap )
  • these objects cannot be returned from the method without copying

Object on the heap EventList* temp = new EventList();

  • heap is “unlimited” ( comparing to stack )
  • these objects are easilly shared accross whole application because they aren’t automatically deteled
  • we have to delete them manually, if we loose the pointer then there are lost bytes in memory ( leaks )

Well, from that example, there are only things that you have noted that are differences, but when using virtual functions and inheritance you’ll see differences.

For example, here is the same code with pointers and without:

WITH POINTERS:

#include <iostream>
using namespace std;
class Base
     {
       public:
          virtual void Create()
          {
               cout <<"Base class create function ";
          }
     };
     class Derived : public Base
     {
       public:
          void Create()
          {
              cout<<"Derived class create function ";
          }
     };
     int main()
     {
         Base  *x, *y;  
         x = new Base();
         y = new Derived();         
         x->Create();
         y->Create();
         return 0;
     }

OUTPUT: Base class create function Derived class create function

WITHOUT POINTERS:

#include <iostream>
using namespace std;
class Base
     {
       public:
          virtual void Create()
          {
               cout <<"Base class create function ";
          }
     };
     class Derived : public Base
     {
       public:
          void Create()
          {
              cout<<"Derived class create function ";
          }
     };
     int main()
     {
         Base  x, y;  
         x.Create();
         y.Create();
         return 0;
     }

OUTPUT: Base class create function Base class create function

So there are problems with objects and virtual functions. It is executed base class function when derived one should be. That is one of differences.