Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Difference between pointer of a class and object of class in initialization

Tags:

c++

class

In C++ Suppose I have

class Sample{
 public:
 void someFunction();
};

In main() is there any difference between doing

Sample obj;
obj.someFunction();

AND

Sample *obj = new Sample();
obj->someFunction();

Is it only a matter of syntax or is there a performance/implementation difference? When should one be used over the other?

like image 612
Arkantos Avatar asked Jan 26 '15 05:01

Arkantos


1 Answers

This is simple stuff - to do with heaps and stacks

Sample obj;
obj.someFunction();

obj is on the stack

AND

Sample *obj = new Sample();
obj->someFunction();

Is on the heap.

This needs to be deleted. It also lives outside scope.

The performance is about the same

like image 77
Ed Heal Avatar answered Sep 17 '22 05:09

Ed Heal