Reputation: 2214
I have doubt in creating objects in C++.
Say I have a class called Employee with some data members and methods.
Now in main function sometimes I have seen developers using different methods to create objects like
Employee emp1; // 1)
Employee emp2 = new Employee // 2)
My doubt is when we should use case 1 and when to use option 2.
Upvotes: 1
Views: 1802
Reputation: 81349
1) Employee emp1;
This creates a default constructed employee at the stack. Its lifetime lasts until it goes out of scope.
2) Employee emp2 = new Employee
This probably doesn't even compile, I guess you meant:
2) Employee *emp2 = new Employee
This creates a default constructed employee at the heap, and assigns its address to an employee pointer. Its lifetime lasts until delete
its called on it.
They are two complete different things. Until you learn more about it, you probably want to stick with the first version. Once you learn more about it, you should stick with the first version as well unless you know and understand the reasons not to.
Upvotes: 3