Search code examples
c++castingoperator-keywordradixderived

Cast from B to base class A


I have the following classes:

template<typename T>
class Vector { ... };

template<typename T>
class Vector2 : public Vector<T> { ... };

Now, i would like to be able to cast a Vector to a Vector2 -even if the object is not really a Vector2- (I mean, dynamic_cast is not what I'm looking for)

What should I implement?

  1. the cast operator on Vector operator Vector2 ()
  2. the constructor on Vector2 Vector2(const Vector<T> &)
  3. both

If i should implement both, when will the cast operator, and when the constructor be calld?


Solution

  • I would implement an explicit constructor Vector2 that takes a Vector<U> -- since you might want to use unrelated types that can be converted from one to another.

    template <typename T>
    class Vector2 : public Vector< T >
    {
    public:
        template <typename U>
        explicit Vector2(const Vector< U >& copyFrom)
        {
            // ...
        }
    };
    

    Implicit convertion might lead to unpredictable behaviors. Kids, don't try this at home.