OOP in C
Cfront Original C++ compiler was just a pre- processor –generated C code which could be compiled with an existing C Compiler
Object-Oriented Programming Data abstraction Support for –Encapsulation –Data Hiding –Inheritance
Objects Consist of –Data - each object has its own data –Operations (methods) A class defines the data and operations for a particular type O-O languages provide support for hiding the data
structs in C Provide a mechanism for creating user- defined data types A struct allows you to group multiple data items into a single "data object" Function pointers allow you to include functions in the object's data
What doesn't a struct have? Data hiding –Everything in the header file is public this pointer –functions need object as an argument How do all objects of a class share the same methods? Inheritance
Methods Putting function pointers into each object means different objects can have different versions of the method Alternate approach is to have a virtual function table (vtable) for each "class" and put a pointer to this table in each object
One approach to inheritance #define S1_CLASS \ int x; \ int y; \ int (* get_x)(); \ int (*get_y)(); typedef struct s1 { S1_CLASS } S1; #define S2_CLASS \ S1_CLASS \ int z; \ int (*get_z)(); typedef struct s2 { S2_CLASS } S2;
vtables and inheritance vtable for a derived class contains a link to the vtable of the base class For multiple inheritance, have links to vtable of all parents
Making generic classes In C++, get generics using templates Use a #define function for the class Use a variable for the type(s) that are generic Calling the function with a particular type will generate code with the desired type in all the appropriate places
Some sources David Brumbaugh, C/C++ User's Journal, July 1, /oopc/oopc.htmlhttp://ldeniau.home.cern.ch/ldeniau/html /oopc/oopc.html pdf /ooc.pdf