Reputation: 16502
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?
Upvotes: 7
Views: 4487
Reputation: 1794
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.
Upvotes: 1
Reputation: 6844
There is short summary
Object on the stack EventList temp;
Object on the heap EventList* temp = new EventList();
Upvotes: 7
Reputation: 10274
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.
Upvotes: 4