Saturday 30 July 2016

Object Orientation in C

C++ is C but with classes. This statement holds it self nice and true almost always (because never say never). What my beef with this statement is how it mislead me to believe that object oriented programming is not C's cup of tea. Recent encounters with meaningful C code has made me realize how void are the arguments against C, criticizing it for not being object oriented. Quoting someone far more legit to comment on this issue:
When he (Bjarne Stroustrup) designed C++, he added OOP (Object Oriented Programming) features to C without significantly changing the C component.  Thus C++ is a "relative" (called a superset) of C, meaning that any valid C program is also a valid C++ program.
There are two ways to interpret this, one would be to hastily take C as being entirely unknown to object oriented capabilities and the other would to think that C++ offers much better interface for object oriented programming, that object orientation of code can be achieved in C if you are willing to rise up to the challenge. 
The more accurate distinction between C and C++ in this regard would be (as the first sentence of this post put) that C does not contain classes. But whatever C does have, is enough to provide you with all the object oriented features that you may desire. It is worth mentioning that C's way of doing such things can be convoluted to the degrees proportional directly with your habit of C++'s ease and inversely with your experience of C's rawness.
While studying a reference book (written a lot a like a tutorial) I read somewhere that structs and unions in C are exactly like classes in C++, having things like members, member functions and access specifiers with the only difference being the default access specification (which is private in a class and public for unions and structs). I took this as something to be learnt afterwards. I thought there would a way to have functions in structs that would require me to learn some additional syntax at some later point in time. As is the case on most occasions, I was wrong. I didn't need to learn any new syntax to be able to turn my structs and unions into classes of C++. All I knew about C, was enough to do the trick for me, I just needed some enlightenment, which often comes with experience.
In fact, there is not much to the notion of achieving object oriented features using strict C. What you need in order to get started with object oriented C, is the following few topics (and the rest I think you can learn as you begin programming):
  1. Pointers
  2. Structs
  3. Unions
  4. Function Pointers
  5. Dynamic Memory Allocation
  6. Typedef
Once you've had enough history with these things, you can jump right into the world of objects in C. If you want a thorough learning of the concepts read this book. But if you want a brief introduction, then follow this tutorial

No comments:

Post a Comment