You are currently browsing the archives for the C++ tag.

Templates of templates

August 21st, 2014


In this brief article we’ll have a look at the topic of building template classes whose parameters are themselves templates.

I’m assuming you’re reasonably familiar with template classes.  If not, here’s a quick introduction.

Read more »

Variadic templates

August 7th, 2014


In this article we’re going to look at a new feature of templates in C++11 – the concept of the variadic template.

Variadic templates allow us to create functions and classes, not only with generic types, but also a variable number of generic types.

Read more »

Template member functions

July 24th, 2014


Previously we’ve looked at template functions and we’ve looked at template classes. This time, let’s look at what happens when you combine them.

Read more »

Templates and polymorphism

July 10th, 2014


Template functions and classes tend to cause consternation amongst programmers. The conversation tends to go something like this:

  • I understand the syntax of templates (although it’s ugly)
  • I get the idea of replacing function-like macros with template functions
  • I can see the application of template classes for containers
  • Most containers and generic functions are library code
  • I don’t write libraries
  • What’s the point of me using templates?

In this article we’re going to look at an application of templates beyond writing library code – replacing run-time polymorphism (interfaces) with compile-time polymorphism. This idea is known as a Policy. The idea is reminiscent of the Strategy Pattern, but uses templates rather than interfaces.

Read more »

Native C/C++ Application development for the mbed using CMSIS-DAP

April 12th, 2013

If you have been following the Feabhas blog for some time, you may remember that in April of last year I posted about my experiences of using the MQTT protocol. The demonstration code was ran the ARM Cortex-M3 based mbed platform.mbed-microcontroller-angled

For those that are not familiar with the mbed, it is an “Arduino-like” development platform for small microcontroller embedded systems. The variant I’m using is built using an NXP LPC1768 Cortex-M3 device, which offers a plethora of connection options, ranging from simple GPIO, through I2C and SPI, right up to CAN, USB and Ethernet. With a similar conceptual model to Arduino’s, the drivers for all these drivers are supplied in a well-tested (C++) library. The mbed is connect to a PC via a USB cable (which also powers it), so allows the mbed to act as a great rapid prototyping platform. [I have never been a big fan of the 8-bit Arduino (personal choice no need to flame me  ) and have never used the newer ARM Cortex-M based Arduino's, such as the Due.]

However, in its early guise, there were two limitations when targeting an mbed (say compared to the Arduino).

First was the development environment; initially all software development was done through a web-based IDE. This is great for cross-platform support; especially for me being an Apple fanboy. Personally I never had a problem using the online IDE, especially as I am used to using offline environments such as Keil’s uVision, IAR’s Embedded Workbench and Eclipse. Over the years the mbed IDE has evolved and makes life very easy for importing other mbed developers libraries, creating your own libraries and even have an integrated distributed version control feature. But the need Internet connection inhibit the ability to develop code on a long flight or train journey for example.

Second, the output from the build process is a “.bin” (binary) file, which you save on to the mbed (the PC sees the mbed as a USB storage device). You then press the reset button on the mbed to execute your program. I guessing you’re well ahead of me here, but of course that means there is no on-target debug capabilities (breakpoints, single-step, variable and memory viewing, etc.). Now of course one could argue, as we have a well-defined set of driver libraries and if we followed aTest-Driven-Development (TDD) process that we don’t need target debugging (there is support for printf style debugging via the USB support serial mode); but that is a discussion/debate for another session! I would hazard a guess most embedded developers would prefer at least the option of target based source code debugging? Read more »

Setting up googlemock with Visual C++ 2010 Express Edition

March 15th, 2012

Following on from my last post about setting up googletest to use with Visual Studio 2010 express edition, this post builds on that by showing how to build, setup and test the googlemock libraries.

If you have read the previous post, then the basic steps are very similar.

First, download the googlemock zip file and unzip it to known location. As before, I suggest something easy, either C:\gmock-1.6.0, or as in my case C:\src\gmock-1.6.0. One useful fact is that all the gtest code is included as part of the gmock distribution. It can be found at \gmock-1.6.0\gtest.

Building the gtest libraries

It is the same process as build the gtest libraries. One importany note is that

The gmock libraries contain all the gtest code as well.

Navigate to the directory \gmock-1.6.0\msvc\2010 and open the Visual C++ project gmock (gmock.sln). You will end up with three projects.


Go ahead and build these (F7) and ignore any warnings. Once successfully built, look in the directory \gmock-1.6.0\msvc\2010\gtest\Debug and you will find two library files

  • gmock.lib
  • gmock_main.lib

Test the GMock Library

As part of the standard build two executable are created that allow a quick self-test of googlemock (gtest does have the same but I neglected to mention those in my previous post).

I recommend opening a command window and navigating to directory  \gmock-1.6.0\msvc\2010\Debug. There you will fine the file gmock_test.exe; go ahead and execute that [NOTE: I had two (of the 830) tests fail, which I’m not sure why (yet) – to be investigated]

This indicates that (most of) gmock functions correctly.

Building a Base GMock Project

A gmock project is the same as  a gtest project but with different project properties. Create a newWin32 Console Application  project.  Add a test fixture file to the project:

  1. #include “gtest/gtest.h”
  2. TEST(setup_test_case, testWillPass)
  3. {
  4.     EXPECT_EQ(42, 42);
  5. }
  6. TEST(setup_test_case, testWillFail)
  7. {
  8.     EXPECT_EQ(42, 0);
  9. }

and exclude file containing default main from build.

Modify the project properties (Alt+F7) as follows:

  • Set gmock and gtest header include directories
    • C/C++ -> General -> Additional Include Directories
      • \gmock-1.6.0\include
      • \gmock-1.6.0\gtest\include
  • Add gmock libraries (instead of gtest libs)
    • Linker -> General -> Addition Library Directories
      • \gmock-1.6.0\msvc\2010\Debug
    • Linker -> Input -> Additional Dependencies
      • gmock.lib
      • gmock_main.lib
  • Modify Runtime Library:
    • C/C++ -> Code Generation -> Runtime Library
      • Multi-threaded Debug (/MTd).

Note here that we don’t have to include the gtest libraries as these are embedded in the gmock libraries. Build and run and we will see the familiar gtest output:

To test the gmock setup we need to create two classes:

  • The class to become the Unit-Under-Test (UUT)
  • An interface class that the UUT calls upon, which doesn’t have any implementation (or the implementation is target/hardware specific).

Interface Class

  1. class IWidget
  2. {
  3. public:
  4.     virtual void On() = 0;
  5.     virtual void Off() = 0;
  6. };

Unit Under Test

  1. class IWidget;
  2. class WidgetController
  3. {
  4. public:
  5.     WidgetController(IWidget& w);
  6.     ~WidgetController(void);
  7.     void exec();
  8. private:
  9.     IWidget& myWidget;
  10. };
  1. #include “WidgetController.h”
  2. #include “IWidget.h”
  3. WidgetController::WidgetController(IWidget& w):myWidget(w)
  4. {
  5.     myWidget.Off();
  6. }
  7. WidgetController::~WidgetController()
  8. {
  9.     myWidget.Off();
  10. }
  11. void WidgetController::exec()
  12. {
  13.     myWidget.On();
  14. }

Testing using the Mock framework

To test using the Mock we need to:

  1. Include the gmock header [line 3]
  2. Create a mock class derived from the Interface class [lines 7-12]
  3. Create a test where the UUT calls on the interface on the mock object [lines 16-23]
  4. Set the mock objects expectation [line 20]. The mock expectation is that the Off member function will be called twice, once during WidgetController construction and once during destruction.
Using the mock
  1. // testFixture.cpp
  2. #include “gtest/gtest.h”
  3. #include “gmock/gmock.h”
  4. #include “IWidget.h”
  5. class MockWidget : public IWidget
  6. {
  7. public:
  8.     MOCK_METHOD0(On, void());
  9.     MOCK_METHOD0(Off, void());
  10. };
  11. #include “WidgetController.h”
  12. TEST(TestWidgetController, testConstructor)
  13. {
  14.     MockWidget mw;
  15.     EXPECT_CALL(mw, Off()).Times(2);
  16.     WidgetController wc(mw);
  17. }

Build and run


You can see gmock in action by simply changing the expectation, e.g. [line 6]

Failing Test
  1. TEST(TestWidgetController, testConstructor)
  2. {
  3.     MockWidget mw;
  4. //    EXPECT_CALL(mw, Off()).Times(2);
  5.     EXPECT_CALL(mw, Off());
  6.     WidgetController wc(mw);
  7. }

will result in the following failed test output:


Where next?

Once you have a working project, the documentation on the Googlemock site is excellent. Start with Googlemock for Dummies.

Overcoming Name Clashes in Multiple C++ Interfaces

December 23rd, 2011


One of our key design goals is to reduce coupling between objects and classes. By keeping coupling to a minimum a design is more resilient to change imposed by new feature requests or missing requirements[1].

An Interface represents an abstract service. That is, it is the specification of a set of behaviours (operations) that represent a problem that needs to be solved.

An Interface is more than a set of cohesive operations. The Interface can be thought of as a contract between two objects – the client of the interface and the provider of the interface implementation.

The implementer of the Interface guarantees to fulfil the specifications of the Interface. That is, given that operation pre-conditions are met the implementer will fulfil any behavioural requirements, post-conditions, invariants and quality-of-services requirements.

From the client’s perspective it must conform to the operation specifications and fulfil any pre-conditions required by the Interface. Failure to comply on either side may cause a failure of the software.

Read more »

enum ; past, present and future

June 15th, 2011

The enumerated type (enum) is probably one of the simplest and most underused  features of the C and C++ which can make code safer and more readable without compromising performance.

In this posting we shall look at the basic enum from C, how C++ improved on C’s enum, and how C++0X will make them a first class type.

Often I see headers filled with lists of #defines where an enum would be a much better choice. Here is a classic example:

/* adc.h */
#define ADC_Channel_0                               (0x00) 
#define ADC_Channel_1                               (0x01) 
#define ADC_Channel_2                               (0x02) 
#define ADC_Channel_3                               (0x03) 
#define ADC_Channel_4                               (0x04) 
#define ADC_Channel_5                               (0x05) 
#define ADC_Channel_6                               (0x06) 
#define ADC_Channel_7                               (0x07) 
#define ADC_Channel_8                               (0x08) 
#define ADC_Channel_9                               (0x09) 
#define ADC_Channel_10                              (0x0A) 
#define ADC_Channel_11                              (0x0B) 
#define ADC_Channel_12                              (0x0C) 
#define ADC_Channel_13                              (0x0D) 
#define ADC_Channel_14                              (0x0E) 
#define ADC_Channel_15                              (0x0F) 

which probably would be better re-written as:

enum ADC_Channel_no {

Before getting onto the advantages and disadvantages of enum’s, let’s have a quick review.

Read more »

GNU, and void pointers

April 18th, 2011

Void pointers were introduced in ANSI C as ‘generic’ pointers; or, if you prefer, ‘pointers to no particular type’. They were designed to replace unsigned char* pointers in instances where the type of the object being pointed to could change.

unsigned char* has the least restrictive alignment – it aligns on a byte boundary. This means an unsigned char* pointer could be used to point to any object (with an appropriate cast, of course).

Remember, though, the type of a pointer defines how to interpret the memory at the address held in the pointer. Using an unsigned char* to point to any object is a bit of an abuse of such a pointer (unless, of course, the thing you’re referencing actually IS an unsigned char!)

Hence, the introduction of the void* – a pointer that imposes no requirements on the memory it references.

The void pointer has the same alignment as an unsigned char*; that is, void pointers align on byte boundaries.

Because void pointers are generic (and are effectively useless on their own) you can implicitly convert any pointer to and from a void*.

There is one little wrinkle with void pointers: you cannot perform (pointer) arithmetic on them. The following code fails to compile:

int main (void)
  int i;
  void *p = &i;
  p++;  /* But what’s the sizeof(void)?! */ 

When you increment (or perform any other arithmetic) on a pointer it modifies the value of the pointer by the size of the type it references.

In the case of a void pointer it doesn’t point to any type, so the compiler cannot know how to manipulate the pointer value.

Except, it seems, in the GNU compiler.

The above code will compile with no errors or warnings. GNU have included an extension that treats void* just like unsigned char*. So with a GNU compiler the value of p would increase by one. We can only assume that, since a void* has the same alignment as an unsigned char*, GNU thought its arithmetic should work the same way, too.

This code is highly unportable (and not even standards compliant). If you’re using little tricks like this in your everyday code be prepared for a painful life when you port to another compiler.

Inheritance, ABCs and Polymorphism

March 14th, 2011

Virtual functions

Virtual functions in C++ exist to maintain the consistent behaviour of polymorphism when accessing derived objects via base class pointers. (If that statement has made your head spin, I’d suggest reading this article before carrying on)

class Base
  virtual void v_op();

class Derived : public Base
  virtual void v_op();

I can access either a Base object or a Derived object via a Base pointer; and I should get the appropriate behaviour for the actual type of the object I’m pointed at:

Base* pB;
pB = new Base;	  // Point at Base object…
pB->v_op(); 	  // calls Base::v_op()
pB = new Derived  // Derived object is also a Base object
pB->v_op()	  // this time calls Derived::v_op()

This mechanism is known as dynamic polymorphism.
Dynamic polymorphism is a very powerful mechanism for building flexible, maintainable solutions. If we base the client code not on a particular object but on a more abstract (in the design sense) super class (something known as the Dependency Inversion Principle) we can swap implementations in and out without having to re-factor the client code (using a principle called Substitutability).

Abstract Base Classes

Let’s take a common design problem. During design we identify a set of classes with some similar behaviour but some unique behaviour. For example, our design may require concurrent behaviour so we define a set of ‘active’ classes, each one doing a different task:

class ActiveComms
  void start();    // Create a thread; and call doStuff()
  void doStuff();  // Perform this class’ behaviour

class ActiveDisplay
  void start();    // Create a thread; and call doStuff()
  void doStuff();  // Perform this class’ behaviour

class ActiveControl
  void start();    // Create a thread; and call doStuff()
  void doStuff();  // Perform this class’ behaviour

These objects share common behaviour – they all have to create and manage a thread of control in the underlying OS – but they all have (at least one) unique behaviour – the actual work they are doing (for example, managing the display)
Rather than replicating the common code it is put into a base class and the ‘working’ classes inherit from it. We make the unique behaviour virtual so that derived classes can provide their own (overridden) implementation.

class Active
  void start();            // Create a thread; ; and call doStuff()
  virtual void doStuff();  // What should this function do?

class ActiveComms : public Active
  virtual void doStuff();  // ActiveComm’s unique behaviour

In the client code we can use dynamic polymorphism to decouple us from any particular implementation:

Active* pActiveObject;
pActiveObject = new ActiveComms;   // Derived class
pActiveObject->start(); 	   // Assume start() calls
                                   // polymorphic doStuff()

What’s to stop us creating a base class object, though?

Active* pActiveObject;
pActiveObject = new Active;        // Base class object.  Correct, but…
pActiveObject->start(); 	   // what happens here?

What happens when the base class object runs? What does its doStuff() function do? At best it may do some generic (common) behaviour; at worst nothing at all.
In reality we don’t want clients to create objects of the common base type. They’re a convenience to improve intrinsic quality, not really part of the functional behaviour. In order to inhibit creation of base class objects we make the virtual function pure.

class Active
  void start();                // As before
  virtual void doStuff() = 0;  // Pure virtual function.

Active is now referred to as an Abstract class. You cannot create an instance of an abstract class. This is because a pure virtual function does not require an implementation. (We’ll talk about what happens if you try and call this base class function in a while). Derived classes must implement the doStuff() function; they then become what are called Concrete classes.

// Active* pActiveObject = new Active     // Fails – Active is abstract
Active* pActiveObject = new ActiveComms;  // Concrete class

What happens if a derived class calls the base class’ (pure) virtual fuction? C++ scope operator (::) allows you to call a function outside your current scope; and in fact anywhere in the class hierarchy.

// Class declarations as before.
void ActiveComms::doStuff() 	// virtual function
  // Do ActiveComms unique behaviour…
  Active::doStuff();            // Call base class’ (pure) virtual function.
                                // This is legal, but what happens?!

What happens when you write code like this depends on your compiler. On most modern compilers – for example GCC, IAR or even Microsoft! – you will get a Linker error when you compile this code. This is because there is no implementation for the pure virtual function (as expected).
Be careful, though: on some older compilers declaring a function as a pure virtual may cause the compiler to insert a null (zero) into the vtable for the class. The code compiles and links with no errors or warnings. When the code executes and the pure virtual function is called (via the vtable) it will execute a null pointer. On many processors this is the reset vector; meaning your call to the base class pure virtual function will reset your system (with no warning!)

Pure Virtual Functions with Implementations

So, can you provide an implementation for a pure virtual function? And why would I want to?
In our example, let’s assume there is some common behaviour that all our concrete classes have to perform as part of their doStuff() function. It makes sense to collect the common behaviour together in the base class – but, we still don’t want clients to create instances of the base class, Active.
Remember, adding (at least one) pure virtual functions to a class makes it an abstract class, meaning you cannot create an instance of it. A pure virtual class is not required to have an implementation – but that doesn’t mean you can’t provide an implementation.
The solution to our problem is to keep the Active class exactly as before but add an implementation to its doStuff() pure virtual function that contains all the common behaviour. This common behaviour can be called from the overridden derived classes’ doStuff() function:

class Active
  void start();                // As before
  virtual void doStuff() = 0;  // Pure virtual function.

void Active::doStuff()		// Pure virtual function implementation!
  // Common behaviour goes in here.

class ActiveComms : public Active
  virtual void doStuff();  // ActiveComm’s unique behaviour

void ActiveComms::doStuff() 	// virtual function
  // Call base class’ (pure) virtual function.
  // Contains all the common behaviour.

  // Do ActiveComm's unique behaviour…

The design and use of pure virtual functions is two-fold:

  • To create abstract classes which acts as a common interface (or contract) to client code. Derived concrete classes can be substituted for the abstract base class (using dynamic polymorphism). The abstract base class designer must specify the (only) set of services the client can expect.
  • To force derived classes to provide their own implementation of the function. The abstract base class designer must specify which parts of the implementation can be shared and which must be unique.

Use of abstract base classes and substitution, using pure virtual functions and dynamic polymorphism allows you to build flexible and adaptable solutions, particularly in areas of your system that will be subject to change over the life of the system.

%d bloggers like this: