A simple program which implements composition in Objective C.
Rectangle class object is an instance variable of Square class. My question is that is there any memory leak in my code?
Rectangle class object is an instance variable of Square class. My question is that is there any memory leak in my code?
Code:
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// 'squ' is a composite object because it is composed of other objects.
Square *squ = [[Square alloc] initWithSide:5.0];
NSLog(@"Side of Square is %.2f", [squ side]);
NSLog(@"Area of Square is %.2f", [squ area]);
NSLog(@"Perimeter of Square is %.2f", [squ perimeter]);
[squ release];
[pool drain];
return 0;
}
/////////////////////////////////////////////////////////////////
@interface Square : NSObject
{
Rectangle *rect;
}
-(Square *)initWithSide:(float) s;
-(void)setSide:(float) s;
-(float)side;
-(float)area;
-(float)perimeter;
-(id)dealloc; // Override to release the Rectangle object's memory
@end
////////////////////////////////////////////////////////
@implementation Square
-(Square *) initWithSide:(float) s
{
self = [super init];
if(self)
{
rect = [Rectangle new];
rect.width = s;
}
return self;
}
-(void)setSide:(float) s
{
rect.width = s;
}
-(float)side
{
return rect.width;
}
-(float) area
{
return ((rect.width) * (rect.width));
}
-(float) perimeter
{
return (4 * (rect.width));
}
-(id) dealloc
{
[rect release];
[super dealloc];
return self;
}
@end
///////////////////////////////////////////////////////////////
@interface Rectangle : NSObject
{
float width;
float height;
}
@property float width, height;
-(float) area;
-(float) perimeter;
-(void)setWidth:(float) w andHeight:(float) h;
@end
//////////////////////////////////////////////////////////////
@implementation Rectangle
@synthesize width, height;
-(void)setWidth:(float) w andHeight:(float) h
{
width = w;
height = h;
}
-(float)area
{
return (width * height);
}
-(float)perimeter
{
return ((width + height) * 2);
}
@end
Last edited by a moderator: