While C was not designed specifically as an object oriented language, it is very flexible and can be written in an OO way. I have seen quite a bit of production C code written in an OO style, so understanding the principals of OO in C could be useful in a future job/internship and also helps you to understand how Objects/Polymorphism/Inheritance in languages like Java and C++ are implemented.
Start by reading through parts 0 and 1 in this
document. Now make a directory named R5.2 and copy and paste shape.h
, shape.c
and
main.c
from part 1 into the
directory. You can now compile the code with the command:
gcc shape.c main.c -o OOC
and run the executable with the command:
./OOC
Most likely you will get a compilation error related to int16_t
, this can be fixed by including the stdint.h
header file in shape.h
.
Once you have the existing code working correctly, add a Shape_print
function to
the shape class. You will notice that the constructor for the shape class does not allocate any memory for a
Shape struct
and relies on being passed a pointer to a preallocated Shape
. Experiment
with making a
second constructor that uses malloc
to allocate memory as well as initialize the values of x and y.
This constructor could be called Shape_alloc_ctor
. Now that the constructor function is allocating
memory you need to provide a destructor function that frees the memory this could be called
Shape_dtor
and should use the function free
. Once you have this implemented, add code to
main.c
that creates a Shape
with the allocating constructor then calls the
Shape_moveBy
and Shape_print
function on the Shape
. Call the destructor to free the memory allocated to
the shape when you are done using it. Recompile your code and run valgrind
to see if you have
any memory leaks.
First read through all of part 2 and get a feel for what is happening in the code that allows the
Rectangle
struct to inherit from Shape
. Now copy and paste the rect.h
,
rect.c
, and the updated main.c
into your R5.2 directory. You can compile and run this
code with the command:
gcc shape.c rect.c main.c -o OOC
and run the executable with the command:
./OOC
You may want to temporarily comment out the code you added in part 0-1 to simplify the next step. Test your
understanding of Part 2 by adding a struct called Triangle
that also inherits from
Shape
. Now you can add code to main.c
that uses the Triangle
struct. Once you have
this working add the function Shape_print
and allocating constructor and destructor from part 0-1
to the Rectangle
and Triangle
classes. Recompile your code and run valgrind
to see if you have
any memory leaks.
If you make it this far, continue to work through the document and update your Triangle
code to follow along with the
addition of polymorphism/virtual functions.