0

Here is some sample code of the behavior I'd like to see:

// Example program
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>

class BaseA
{
public:
    BaseA() { };
};

class BaseB
{
public:
    BaseB() { };
};

class Derived1 : public BaseA
{
public:
    Derived1() : BaseA() { };
};

class Derived2 : public BaseA, public BaseB
{
public:
    Derived2() : BaseA(), BaseB() { };
};

int main()
{
    std::vector<BaseA *> collection_of_As{
        new Derived1{}, new Derived1{}, new Derived2{},
        new Derived2{}, new Derived1{}, new Derived2{}
        };

    for (BaseA * Aptr: collection_of_As) {
        BaseB * Bptr = dynamic_cast<BaseB *>(Aptr);

        std::cout << std::boolalpha << (Bptr != std::nullptr) << std::endl;
    }

    return 0;
}

But it won't compile since BaseA isn't polymorphic, even though it's most derived class can be. I understand why this doesn't work, but I still need this behavior. Is there someway I can get this compiling & working?

Brian Rodriguez
  • 4,250
  • 1
  • 16
  • 37
  • 2
    Why not post an [MCVE](http://stackoverflow.com/help/mcve)? You were so close. You just needed to include `iostream` and `vector` at the top of this file. It will make it easier for others to reproduce your problem and work on it. – David Grayson May 27 '15 at 16:20
  • 1
    Why don't you make it polymorphic by defining virtual destructor in `BaseA`? – StenSoft May 27 '15 at 16:24
  • Another good thing to do is to include the exact error message you are getting from the compiler, which is "error: cannot dynamic_cast 'Aptr' (of type 'class BaseA*') to type 'class BaseB*' (source type is not polymorphic)". By performing an internet search for the key words in that error message, you can find other people who have had the exact same problem as you and solved it by making BaseA be polymorphic: http://stackoverflow.com/questions/15114093/c11-source-type-is-not-polymorphic – David Grayson May 27 '15 at 16:25

1 Answers1

4

Make BaseA polymorphic. The simplest way to do this is to give it a virtual destructor.

class BaseA
{
public:
    virtual ~BaseA() {}
};

You'll need one anyway, if you want to fix the memory leaks in your example.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644