Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

struct verses class in ANSI C

Status
Not open for further replies.

tcollins

Programmer
Sep 12, 2000
34
US
Say, does anyone know if ANSI C supports class like structures???

I'm trying to do a:

struct Complex
{
int num;
me(){printf("%d\n",6);}
};

and it keeps comming up with:
syntax error; found 'identifier' expecting '}'.
syntax error; found '{' expecting ';'.
syntax error; found 'string constant' expecting ')'.
Missing prototype.

etc...etc...

Thanks.
 
No it doesn't. You can, however, use function pointers as struct members to simulate it. For example:

/*** UNTESTED ***/

foo.h
-----
struct Complex
{
int num;
void (*func)(void);
};

struct Complex *initComplex(void);

foo.c:
------
#include <stdio.h>
#include <stdlib.h>
#include &quot;foo.h&quot;

static void foo(void)
{
printf(&quot;%d\n&quot;,6);
}

struct Complex *initComplex(void)
{
struct Complex *this=malloc(sizeof *this);
if (this!=NULL) {
this->num=0;
this->func=foo;
}
return this;
}

prog.c
------
#include &quot;foo.h&quot;

int main(void)
{
struct Complex *bar=initComplex();
if (bar!=NULL) {
bar->func();
}
return 0;
}

Note that since foo is declared static it is only accessible to code inside foo.c. However, initComplex makes it accessible to users of struct Complex through the function pointer.

You can actually implement OOP in C, but it's a lot of work and your code will look rather ugly because the language doesn't provide support for it; you have to do all the work yourself.

Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top