Search code examples
c++boostboost-ublas

Subclass of a boost vector in C++


How can I make a subclass of a boost::numeric::ublas::c_vector<float, 3> whose three elements can be accessed with .x .y or .z and have a constructor in the form vec3(float x, float y, float z);. I wanted to use the boost vector because I didn't want to have to write the functionality for all the operators and math functions of a class myself, and I was already using the boost library.

For example:

foo = vec3(2.5f, 0.0f, 0.0f);
bar = vec3(2.0f, 0.0f, 0.0f);

foo += bar;
cout << foo.x; // prints 4.5

Solution

  • Don't make a subclass as you can have problems in future, because base class member functions are non-virtual. Prefer composition instead in this case (make an object of this class a member of your class). Also Herb Sutter suggests to never derive concrete classes (especially in C++ as there is a system of virtual/non-virtual member functions present).