Posts Tagged ‘class’

Passing function pointers as a parameter to another function can be tedious work. The function pointer definitions can be long and cumbersome to write, and obscure to read. Using pointers to member functions can be even more ambiguous. Fortunately, we can leverage the power of templates to make this work easier for us by making […]

Functors in C++

Posted: 12th June 2013 by Tim in C++
Tags: , , , , , , ,

One neat feature of C++ is Functors, or function objects. Essentially, functors are just like normal objects, but they can be ‘called’ like any other function; they can take any number of arguments of any type and return a value of any type. However, because functors are objects, they can have state (without resorting to […]

Using memset or bzero on structs in C is a common way to clear the values contained within that struct. This generally works well in C as your structs will contain POD types, unions and other structs. However, in C++, these structs (or struct members) may also contain methods which assume the struct is in […]

Struct sizes in C++

Posted: 24th March 2012 by Tim in C++
Tags: , , , , , , , , , , ,

Consider the following program: #include <iostream> struct A {     char a;     long b;     char c; }; struct B {     char a;     char c;     long b; }; int main() {     A a;     B b;     std::cout << “sizeof(a): ” << sizeof(a) << std::endl;     std::cout << “sizeof(b): ” << sizeof(b) << std::endl;     return 0; } To summarize, it […]

C++ can be a strange language. Most of the time it’s easy to work with, but occasionally you’ll get errors which take forever to debug. Take a look at the following code and write down what you think the output will be. #include <iostream> class Base { public:     virtual void test(int x = 0)     { […]

For various reasons, you cannot create a pthread on an object’s function. There is, however, a few ways to get around that. One of the most flexible ways of doing this is to create a wrapper function to call an object’s method, taking a pointer to the object as an argument. For example, if you […]