Search code examples
c++gccdeclarationforward-declarationtypeid

Forward declaration and typeid


I would like to check the type of a superclass A against the type of a subclass B (with a method inside the superclass A, so that B will inherit it).

Here's what I thought did the trick (that is, the use of forward declaration):

#include <iostream>
#include <typeinfo>

using namespace std;

class B;

class A {
  public:
    int i_;
    void Check () {
      if (typeid (*this) == typeid (B))
        cout << "True: Same type as B." << endl;
      else
        cout << "False: Not the same type as B." << endl;
    }
};

class B : public A {
  public:
    double d_;
};


int main () {

  A a;
  B b;

  a.Check (); // should be false
  b.Check (); // should be true

  return 0;
}

However this code does not compile. The error I get is:

main.cc: In member function ‘void A::Check()’:
main.cc:12: error: invalid use of incomplete type ‘struct B’
main.cc:6: error: forward declaration of ‘struct B’

How could I solve this problem?


Solution

  • I think that the problem you are trying to solve is much better handled by a virtual method:

    class A
    {
        public:
            virtual bool Check() { return false; };
    }
    
    
    class B : public A
    {
        public:
            // override A::Check()
            virtual bool Check() { return true; };
    }
    

    Methods in the base class A should not need to know whether the object is "really" an A or a B. That's a violation of basic object-oriented design principles. If the behavior needs to change when the object is a B, then that behavior should be defined in B and handled by virtual method calls.