Hello. I am a newbie to Obj-C, and I have a strong background in C++. Here are some lines of code that I would like to have explained:
You will probably understand that I have a fraction class declared elsewhere and some methods, which are of no importance to my question.
As you can see, I am pre-allocating the "fraction *a" and "fraction *b" but NOT "fraction *result". Why is that? How come it's not necessary to write
to allocate memory for the "result" object?
I know that if I eventually write "fraction *result = [[fraction alloc]init]" it will also be correct, but why doesn't it give me any errors?
NOTE: In the "-(void) setTo: (int) n over: (int) d" function that you see into the "main()" I do not allocate memory for my object
In general, I have a hard time trying to figure out when must I allocate objects using the "alloc" method and when not. I also have a hard time to avoid memory leaks (for example, I know that I shouldn't write "[[a div: b] print]" because an object will be created that I won't be able to free later).
If you still can't figure out what I am saying, here is the entire source.
Code:
int main(int argc, char* argv[]){
fraction *a = [[fraction alloc] init];
fraction *b = [[fraction alloc] init];
fraction *result;
[a setTo: 1 over: 3];
[b setTo: 2 over: 5];
[a print];
printf(" + ");
[b print];
printf(" = ");
result = [a add: b];
[result print];
printf("\n");
[result free];
[a print];
printf(" - ");
[b print];
printf(" = ");
result = [a sub: b];
[result print];
printf("\n");
[result free];
[a print];
printf(" * ");
[b print];
printf(" = ");
result = [a mul: b];
[result print];
printf("\n");
[result free];
[a print];
printf(" / ");
[b print];
printf(" = ");
result = [a div: b];
[result print];
printf("\n");
[result free];
return 0;
}
As you can see, I am pre-allocating the "fraction *a" and "fraction *b" but NOT "fraction *result". Why is that? How come it's not necessary to write
Code:
fraction *result = [[fraction alloc]init]
I know that if I eventually write "fraction *result = [[fraction alloc]init]" it will also be correct, but why doesn't it give me any errors?
NOTE: In the "-(void) setTo: (int) n over: (int) d" function that you see into the "main()" I do not allocate memory for my object
In general, I have a hard time trying to figure out when must I allocate objects using the "alloc" method and when not. I also have a hard time to avoid memory leaks (for example, I know that I shouldn't write "[[a div: b] print]" because an object will be created that I won't be able to free later).
If you still can't figure out what I am saying, here is the entire source.