C++ Class wrapper around fundamental types

1) Is there any additional function calling overhead when using someClass.operator+()

No, if the function body is small and in the header, it will be inlined, and have no overhead

2) Is there a way to automatically make the compiler cast the floatWrapper to a float?

struct floatWrapper {
    floatWrapper(float); //implicit conversion from float
    operator float(); //implicit conversion to float.  
};

Again, if the body of the function is small and in the header, it will be inlined, and have no overhead

3) Is there any additional memory overhead?

not if there’s no virtual functions. A class is called polymorphic if it declares or inherits any virtual functions. If a class is not polymorphic, the objects do not need to include a pointer to a virtual function table. Moreover, performing dynamic_cast of a pointer/reference to a non-polymorphic class down the inheritance hierarchy to a pointer/reference to a derived class is not allowed, so there is no need for the objects to have some kind of type information.

4) Are there any other problems / performance impacts this could cause?

performance? No.

Also, be sure to implement binary operators that don’t modify the lhs as free functions, and overload them to support all relevant permutations of floatWrapper and float.

struct floatWrapper {
    explicit floatWrapper(float);
    operator float(); //implicit conversion to float.  
    floatWrapper operator-=(float);
};
floatWrapper operator-(floatWrapper lhs, floatWrapper rhs) 
{return lhs-=rhs;}
floatWrapper operator-(float lhs, floatWrapper rhs) 
{return floatWrapper(lhs)-=rhs;}
floatWrapper operator-(floatWrapper lhs, float rhs) 
{return lhs-=rhs;}

Here’s my attempt at such a thing. Note you’ll need a slightly different version for float/double/long double.

Leave a Comment