I have a couple of questions reagarding the new keyword in C++. First, can someone tell exactly what is the difference between the following two code segments:
Account a = Account(35.00, 34234324); Account *ptrA = &a;Account *a = new Account("John", 10.50, 123456);
Secondly, Ive read that the following segment of code will lead to a memory leak after the b = a assignment is made. My question is, will the second segment of code also lead to a memory leak?
Thanks
int main() { Account *a = new Account("John", 10.50, 123456); Account *b = new Account("Derek", 12.07, 123457); a->display(); b->display(); b = a; a->display(); b->display(); }
BTW, you might want to check out smart pointers (http://en.wikipedia.org/wiki/Smart_pointer) to avoid such leaks. The Wikipedia article has both examples and further links.
a have alloc memory in stack and it will automatically free when the function finish.
ptrA = &a : it only create a pointer not a new object.
second: dynamic variable
Account *a = new Account("John", 10.50, 123456);
create a object in heap memory an return a pointer.
you can access object through pointer.
and when you not need object you have to free it by statement:
delete a;
jkr
Do you also happen to know the operator precedence rules for '*facepalm*'? Sorry, but that had already been mentioned.