Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Main differences between objects and object pointers?

Tags:

c++

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?

like image 682
RoR Avatar asked Feb 18 '11 21:02

RoR


People also ask

What is the difference between object and pointer?

A pointer is a variable that stores the memory address of another variable. The types of the pointer are Null pointer, Void pointer, Wild pointer, and Dangling pointer. An object is defined as the instance of a class. These objects can access the data members with the help of a dot(.)

What is the difference between pointer and object in C++?

In C++, a pointer holds the address of an object stored in memory. The pointer then simply “points” to the object. The type of the object must correspond with the type of the pointer. The & character specifies that we are storing the address of the variable succeeding it.

What is an object pointer?

A pointer is a type of variable that carries location information. In this case, the example variable will store the address of an Order object that we want to interact with. We initialize the pointer variable by using the C++ new operator to construct a new object of type Order.

Are pointers considered objects?

In computer science, a pointer is an object in many programming languages that stores a memory address. This can be that of another value located in computer memory, or in some cases, that of memory-mapped computer hardware.


2 Answers

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 )
like image 126
Gaim Avatar answered Sep 29 '22 13:09

Gaim


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.

like image 25
LandonSchropp Avatar answered Sep 29 '22 11:09

LandonSchropp