Share

Comparing C++ and C (Classes and Methods)

This two part series compares C and C++ by comparing the C++ code and its equivalent C code. This comparison should give you a better feel of the performance differences between C and C++.

C++ Method Invocations

 In the first article in this series we will look at the performance impact of C++ method invocations. This comparison will be carried out by first comparing C++ code and its C equivalent.

C++ Code

The following C code provides an equivalent implementation for the C++ code shown above. The C++ class has been mapped to a C structure.

C code

Analysis

This section analyses the C++ code and its C translation and identifies the performance impact.

C++ Method Invocation All C++ methods when translated to C end up with an additional parameter. This might appear to be a big performance overhead. In reality however, the code in C will also have to access the common data structure via an array index or some other mechanism.
Object Construction Whenever an object is constructed, C++ will invoke the constructor. Sometimes this might be an addition overhead. This overhead can be reduced by defining the constructor inline. In most cases however, the constructor is actually replacing a routine that would have been used to initialize the data structures in a conventional C program. If a program declares a lot of global objects, object construction can be a big overhead at program startup. C++ invokes constructors for all global objects before main() is called.
Object Destruction As you can see from the C code, whenever an object goes out of scope or is explicitly deleted, C++ invokes the destructor for the object. This overhead can be reduced by only defining destructors when they are really needed (i.e. some action is required when object is deleted). Inline destructors can also be used to reduce the overhead.
Static Access The C code above shows that static member functions and variables do not correspond to an instance of the object. Thus they are accessed without indirection of the object. This can be useful in defining methods which need C level function call conventions. One good use for static member functions is to implement interrupt service routines (ISRs). ISRs handlers typically need to be C type functions. In most implementations,  C++ static functions can be directly used as ISR handlers.

Explore More