Re: Q's about Obj-C
Re: Q's about Obj-C
- Subject: Re: Q's about Obj-C
- From: "Erik M. Buck" <email@hidden>
- Date: Mon, 15 Oct 2001 13:13:58 -0500
>
Then is it fair to say that the declarations of messages in .h
>
is strictly speaking not required by the language? I'm still a
>
little confused. For example is:
>
>
@interface A : NSObject
>
@end;
>
>
@implementation A
>
- (int) foo { /* new method */
>
return 1;
>
}
>
@end
>
>
legal?
Yes it is legal. It is even desirable in some cases.
>
>
> id o;
>
> [o foo:1]; // issues a warning, and compiles randomly (A) or (B)
>
>
I thought that because the runtime selects the method, it won't
>
really be randam, will it? It will either be calling A's or B's
>
or forwarded (if it's setup to do so), right?
There is only one selector called foo: One class implements the message
selected by foo: assuming that the argument is int. Another class
implements the message selected by foo: assuming that the argument is float.
If you tell the compiler which class you are sending the foo: message, there
is no problem. If you don't tell the compiler then it has to pick one of
the two argument types and may pick the wrong one. That is why the compiler
generates a warning.
@implementation A
- foo:(int)arg
{
printf("%d" arg);
return self;
}
@end
@implementation B
- foo:(float)arg
{
printf("%f" arg);
return self;
}
@end
A *someA;
B *someB;
id someObject;
[someA foo:10]; // OK compiler knows an int argument is needed
[someB foo:10]; // OK compiler knows a float argument is needed and
converts 10 to 10.0
[someObject foo:10]; // WARNING: compiler does not know if it needs to
convert to float or not
The best solution is to NOT use the same selector with different argument
types. Unfortunately, Cocoa already contains a few of these.
>
>
> [(A*)o foo:1]; // converts 1 to double (A)
>
> [(B*)o foo:1]; // uses 1 as an integer (B)
>
>
> JC> 4. What makes a class an abstract class? In C++, that's caused
>
> JC> by a pure virtual function, but there doesn't seem to an
>
> JC> equivalent in Obj-C.
>
>
>
> What is it "an abstract class"? ;))))
>
>
>
Oh, I'm not asking in the context of instantiation, just what
>
does the docs mean when it says "abstract."
>
The documentation uses the term "abstract class" to mean a class that you
normally don't instantiated. Abstract classes are most often used as a
foundation for sub-classes.
C++ often uses abstract classes for the same purpose that Objective-C uses
protocols. C++ abstract classes can not be instantiated and Objective-C
protocols can not be instantiated. The primary difference is that C++
abstract classes can contain some implementations but not all and
Objective-C protocols are not allowed to contain any implementations. An
Objective-C protocol is the same idea as a C++ class with no member
variables and all member functions declared pure virtual. An Objective-C
protocol is the same as a Java interface.