0

I am writing unit tests to exercise various code paths involving a factory class.

The factory returns a std::unique_ptr to a base type:

class Base {};
class Derived1 : public class Base {};
class Derived2 : public class Base {};

std::unique_ptr<Base> Type::Factory(enum rtype) const {
    switch(rtype) {
        case d1: return std::make_unique<Derived1>();
        case d2: return std::make_unique<Derived2>();
        default: return std::make_unique<Derived1>();
    }
}

So in the test I want to ensure that the correct type is returned (factories are breeding ground for cut'n'paste bugs).

Is there a way of checking what type is returned? This: EXPECT_TRUE(typeid(Derived1), typeid(type.get()); is false because the type.get() is that of Base and not the rtype that was passed in.

underscore_d
  • 6,309
  • 3
  • 38
  • 64
graham.reeds
  • 16,230
  • 17
  • 74
  • 137
  • I'd expect that if you do `typeid(*type.get())` then it will check the dynamic type, no? – underscore_d Jun 15 '20 at 10:46
  • 1
    Does this answer your question? [Get object's type from pointer to base class at runtime](https://stackoverflow.com/questions/39138770/get-objects-type-from-pointer-to-base-class-at-runtime) The 2nd answer says to dereference the pointer as I suggested. – underscore_d Jun 15 '20 at 10:47
  • 1
    Having `default` returning a `Derived1` looks scary. – Ted Lyngmo Jun 15 '20 at 10:47

2 Answers2

1

This: EXPECT_TRUE(typeid(Derived1), typeid(type.get()); is false because the type.get() is that of Base and not the rtype that was passed in.

typeid( type.get() ) will get the typeid of the base pointer, i.e. the type that get() is declared as returning. To get the real dynamic type of the pointed-to object, whatever that may be, you should dereference the pointer:

typeid( *type.get() )

underscore_d
  • 6,309
  • 3
  • 38
  • 64
0

You need to use RTTI. The type is erased to Base when used.

You can do a dynamic cast to get the proper type, something like:

EXPECT_FALSE(dynamic_cast<Derived1*>(type.get()) == nullptr)

If dynamic_cast fails (type is not of Derived1) dynamic_cast will return a nullptr.

Mikael H
  • 1,323
  • 7
  • 12