[comp.lang.c] Object oriented programming in C

braner@batcomputer.tn.cornell.edu (braner) (11/13/86)

[]

A while ago I posted a method to do object oriented programming in C.
At the heart of the method is a function that is called every time a
method is being looked up.  This function, called FindMethod, returns
the address of the method - a pointer to a function.  Now how do you declare
a function of that type?  A variable of type pointer to a function which
in turn returns an int is declared as:

	int (*foo)();

and in my posting I declared FindMethod as:

	int (*FindMethod())(token,obp);

Turns out that the correct syntax is:

	int (*FindMethod(token,obp))();

What is surprising is that the compiler I used (Megamax C on the Atari ST)
did not complain, and went on to produce code that did just what I intended!
But other compilers complained.  Thanks to Don Howes that notified me of the
problem.

- Moshe Braner

hymie@dvm.UUCP (Hyman Rosen) (11/21/86)

In article <1497@batcomputer.tn.cornell.edu> braner@batcomputer.UUCP (braner) writes:
>[]
>
>A while ago I posted a method to do object oriented programming in C.
>At the heart of the method is a function that is called every time a
>method is being looked up.  This function, called FindMethod, returns
>the address of the method - a pointer to a function.  Now how do you declare
>a function of that type?  A variable of type pointer to a function which
>in turn returns an int is declared as:
>
>	int (*foo)();
>
>and in my posting I declared FindMethod as:
>
>	int (*FindMethod())(token,obp);
>
>Turns out that the correct syntax is:
>
>	int (*FindMethod(token,obp))();
>
>What is surprising is that the compiler I used (Megamax C on the Atari ST)
>did not complain, and went on to produce code that did just what I intended!
>But other compilers complained.  Thanks to Don Howes that notified me of the
>problem.
>
>- Moshe Braner

	First of all, you ought to consider using typedef to simplify
declarations like that, but that does take all the joy out of life,
doesn't it? :-) In any how, there is a reason why some compilers accept
the incorrect syntax. It's because of one of the very few bugs in K&R.
The C reference manual in the back says that

	function-declarator:	declarator ( parameter-list-opt )

which is the syntax you tried using. Nevertheless, it is incorrect, and
now most compilers accept only the proper syntax.

	Remember that the intent of C declarations is to mimic the use of
the variable being declared. When you actually call FindMethod, you use
FindMethod(token,obp). You do *not* pass those arguments to the function
whose pointer is returned by FindMethod. When defining a function in C,
the arguments always go in the set of parentheses immediately following
the name of the function.
-- 


								- Hymie

		...{decvax,ihnp4,ucbvax}!allegra!phri!orville!dvm!hymie