Moving from C to C++ - Structured to Object Oriented - a lesson for engineers
Archive - Originally posted on "The Horse's Mouth" - 2015-03-28 16:32:01 - Graham EllisThe C language formed a a logical base from which C++ - an object oriented language developed. One of the major reasons that it is indeed a logical base is that C and its libraries include a number of elements though which you can write code which is essentially object oriented if you write with the correct design patterns - and adding C++ simply provides tools to make the patterns easier, to provide an environment which supports inheritance and polymorphism, and to enforce additional checks to limit you do running only sensible (correctly chosen) functions.
From last week's C and C++ course, [here] is a C program written using the OO Paradigm.
Switching across to C++ ...
pointers become object references
structs become object [members]
mallocs become new
function calls with a pointer as first parameter become method calls
and those are pretty direct conversions. I have also replaced printf with count.
The comparative code in C++ is then [this].
Many people who have been 'brought up' on engineeing or structured languages find the whole OO thing a bit of a difficult concept at first, and by writing what's actually a rather good and well structured program in C, and then making changes like the ones above, is a neat way to show them how OO goes together, and the first very clear examples of how it really works. Neat - and very rewarding to teach; it's not an approach that's always needed on our C and C++ courses since delegates backgrounds differ, but it's an approach I'll use if it's going to be the best way for the group I students I have.