Semi-Object Oriented C Development – Part 3

Well, here it is! Part 3 of my series on Object… Semi-Object Oriented C Development. For those of you sitting in your chairs saying, “I don’t remember parts 1 and 2”, well here you go:

  1. http://wp.me/p1fcqR-p Object Oriented C Development – Part 1 (Typedef, Constructors, Destructors).
  2. http://wp.me/p1fcqR-I Semi-Object Oriented C Development – Part 2 (Methods and such).

Those who follow me on twitter should know that my next topic in this realm is going to be on visibility. So far I have only defined “classes” that have every member private. I do so by typedefing every “class” as a “void *”. Well no more! There may be a time that you want public members in your “class”, something you can edit at will without accessors.

To do this you do the same as always, define your “class” to a pointer, but instead of the “void *” you define it to a “struct *”. For our Vector2 example we may want the user to be able to access the X and Y members directly. To do this, typedef your Vector2 as such in your .H file:

typedef struct {
     float X;
     float Y;
} *Vector2;

Now, it is *VERY* important that define the Vector2 in your .C file with the x and y as the first members in that order, as such:

typedef struct {
     float x;
     float y;
     int somePrivateMember;
} _Vector2;

If you do not, the offsets of you public members will be incorrect and things will go to hell faster than Lindsay Lohan on Valentine’s day. The rest of your methods should follow the same form as in Part 2.

This was rather short (possibly anti-climactic) but there is not much to say. If you understand pointers and structs this should make good sense.

In the next part I plan to talk a bit about adding “methods” to your structs. Pointers to functions can be fun. After that I may talk a bit about “classes” without dynamic memory and inheritance. We’ll see.

I’ll leave you with the following quote:

“C++ : Where friends have access to your private members.” — Gavin Russell Baker.

Advertisements

Father, Husband, Software Developer, Podcaster, Blogger, Gamer, and the Future Leader of the Zombie Resistance. My thoughts are my own.

Tagged with: , , , , , ,
Posted in C, Coding, OOP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

%d bloggers like this: