Re: Base class/subclass model in objective c
Re: Base class/subclass model in objective c
- Subject: Re: Base class/subclass model in objective c
- From: Jean-Daniel Dupas <email@hidden>
- Date: Fri, 18 Jun 2010 12:54:28 +0200
Le 18 juin 2010 à 12:44, Jonny Taylor a écrit :
> I am still getting to grips with objective C, coming from a C++ background, and I'm stuck on a particular aspect of the base class/subclass model that I hope somebody can help me with.
>
> I need an object representing a video camera plugged into the mac, a camera which may be one of several models with their own API. I think the tidiest way of implementing this in C++ would be to have a base class that handles the logic for actions such as "acquire video", but calls pure virtual functions for actions such as "allocate memory for a frame buffer" whose details will vary depending on camera model and associated API.
>
> I believe an equivalent approach in objective C would use a protocol to represent generic actions and provide a generic interface on top of the camera-specific APIs, plus a base class containing generic code and subclasses containing camera-specific code. The base class will NOT conform to the protocol because it does not implement all the methods in the protocol (i.e. those that require direct knowledge of a specific camera API), whereas the subclasses DO conform to the protocol - and because I have told it this the compiler will do a good job of warning me if there are some methods not implemented in either the base class or a given subclass.
>
> The problem comes when the base class tries to call a method such as "allocate memory for a frame buffer" that is not implemented in the base class, but only in subclasses (and the protocol). Because the base class does not conform to the protocol, if the base class calls such a method I (quite rightly) get warnings saying it may not respond to the method... although I do in fact know that a naked base class will never be instantiated and so in practice the method will always exist.
>
> I can see two ways of working around this - either implement placeholder methods in the base class (that raise an exception or something) in order to make the base class conform to the protocol (knowing that in practice they should always be overridden by a subclass), or have the subclass pass its "self" pointer to the base class in the form of an id<MyProtocol> that the base class uses when it needs to call such methods. Both of these leave me feeling pretty dirty, though.
>
Adding stub methods that raise an exception seam a good way to solve the problem (that what all class cluster abstract class do in Cocoa Framework).
-- Jean-Daniel
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden