Main Content

Learning C++ - a design pattern for your first class

Archive - Originally posted on "The Horse's Mouth" - 2012-05-02 12:19:22 - Graham Ellis

From today's C++ Course - a new, clear example of a design pattern for a simple class, its headers, and a test harness - [here].

When using an Object Oriented language, design patterns are really useful. Essentially, they're a known and standard way of combining the features of the language in a convenstional way. By using a design pattern, you're going to be writing along the same lines as others have written before, so you'll:
• avoid some common code pitfalls
• find it easier to write your code as it will be familiar
• produce code that's easy for others to pick up and follow later on

My "SimpleClass" design pattern (as I've chosen to call it) shows a class definition, definition of each of the members, and definition of a calling program. It's very much a starting point within the course, and I went on after this example to add:
• private access for member variables, and public accessor functions
• use of this rather than using different names in the constructor
• multiple methods of the same name (I provided several constructors)

Going one stage further, I divided the code into three separate files:
• a header file which defines the API to the class - [here]
• a file which defines all the methods within the class - [here]
• and the test harness - [here].

This is becoming a much more realistic use of a class - with the test program being separated from the detail of how the class works, and the header file in a third place and shared betweenthe two program files we already have, and other programs which choose to make use of our class.

Completing this example - compile and run:

  munchkin:rcpp grahamellis$ g++ -o tabby table.cpp tabletest.cpp
  munchkin:rcpp grahamellis$ ./tabby
  Size of table 1.8
  1200
  Size of table 3.38
  munchkin:rcpp grahamellis$


We offer three different C++ courses - for delegates who haven't programmed before (5 days), for delegates who have programmed before, but not in C (4 days), and for delegates who have prior programming experience in C. See [here]. A public course series ran last week, and the next public course series runs in mid-July - already booking well, but there are still spaces left at all levels. We run private courses as required for single customer groups; as I write, just one week is available in May and you would then be looking forward several months ...