Say I have a class called Money which has parameters Dollars and Cents
I could initialize it in the followings 2 ways:
- Money a(3,15);
- Money *b=new Money(3,15);
My question is when should I use (1) and when should I use (2)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The first one creates a
Moneyobject on the stack, its lifespan is within the scope of when it was created. Meaning when you hit a}it goes out of scope and the memory is returned. Use this when you want to create an object within one function.The second one creates a
Moneyobject on the heap, its lifespan is as long as you want it to be, namely until youdeleteit. Use this when you want your object to be passed around to different functions