I have moved my blog to Wordpress at theunixgeek.wordpress.com. I will still be checking back periodically on this one as well, though. 19 April 2009

featured

Merging Mkdir and Cd | 280 Slides Interview | I Switched to KDE 4

clickable portals

Sunday, January 13, 2008

OOP in C, Part 1

Yes, believe it or not, you can write object-oriented programs in C! Of course, it's not the neatest of all programming languages when it comes to OOP but let's take a look at the possibilites. This part examines basic data encapsulation, a big point when it comes to writing object-oriented programs.

Background: Encapsulating data basically means that data in one part of the program isn't visible to other parts of a program. Why is this important? Debugging large programs. For example, say you're writing a web browser, and your back button doesn't work. You can focus only on that part of the program without having to think about data being processed in other parts of the program when it comes to finding out what's wrong.

Snippet:

union Data {
int digit;
};
union Data myData;
int digit = 2;
myData.digit = 3;


Explanation: The above snippet shows how data can be hidden from other parts of a program using unions. Although there is a digit variable in Data, it's OK to declare another variable of the same name outside of Data because that data is hidden to the instance  myData. Speaking of which, yes, you can have multiple instances of a union.

1 comments:

Anonymous said...

A class, extending a super class and having common features with other classes of similar type can be represented as a structure:

struct class {
struct super_class super;
int private_data;
void (*func)(int, void); //Look, ma! Behaviour!
};

Such structures are references by pointer (i.e. by their address in memory), which can be cast into the super class (for accessing super).