Search code examples
c++inheritancetypespolymorphismshadowing

How do I achieve the equivalent of type shadowing by a derived class?


I would like to write something like the following:

class A {
    virtual typedef int foo_t;

    void bar() {
       cout << "foo_t is " << get_demangled_name(typeid(foo_t));
    }
}

class B : A {
    typedef float foo_t;
}

And for bar() to behave polymorphically. But - this is not possible in C++. What should I do instead?


Solution

  • So, if this is just a thought-experiment, then the answer is "You can't do that".

    If you actually want a hierarchy where your derived classes have different types, you could do something like this:

    class Base
    {
       public:
         virtual void bar() = 0;
    };
    
    class A: public Base
    {
       public:
         void bar() { ... do stuff here }
       private:
         typedef int foo_t;
    };
    
    
    class B: public Base
    {
       public:
         void bar() { ... do stuff here }
       private:
         typedef float foo_t;
    };
    

    Alternatively, if inheritance isn't required:

    template<typename T>
    class TemplateA
    {
       typedef T foo_t;
       void bar() { ... do stuff here ... }
    }
    
    typedef TemplateA<int> A;
    typedef TemplateA<float> B;
    

    What the virtual function gives is that you can have a:

    vector<Base&> v; 
    A a;
    B b;
    v.push_back(a);
    v.push_back(b);
    

    and use it in a generic way. Templates don't give quite that flexibility (in this example, it would of course be possible to produce some sort of templated solution that also has a base-class, and then the both solutions are more or less identical)

    It all depends on what your thoughtexperiment actually is trying to solve - even if it's just a thoughtexperiment, these two solutions will have different pro's and con's, depending on how you want to use them.