Search code examples
c++inheritancetypesaliasdowncast

Some kind of type alias : An empty derived class


What I would like to know is :

  • Is this snippet portable ?
  • If not, why ?

struct GenericBase{
};

struct MyObject : public GenericBase{
    virtual void method() = 0;
};

struct MyAlias : public MyObject{
    //supposed to have exactly the same layout as MyObject (?)
};

struct MyImpl : public MyObject{
    virtual void method() { cout << "method implementation \n"; }
    //note that MyImpl inherit MyObject, but we cast it to MyAlias
};

void test_alias(){
    MyImpl m;
    GenericBase* ptr = &m;
    MyAlias* new_ptr = static_cast<MyAlias*>(ptr); //here is the cast
    new_ptr->method();
}

EDIT:
I cant't use RTTI, nor templates


Solution

  • Answer: This is not portable.

    struct MyAlias : public MyObject{
        //supposed to have exactly the same layout as MyObject (?)
    };
    

    This comment is wrong : the size of MyAlias is implementation dependent and is not specified by the standard (it depends, for example, on the alignment requirements of the target architecture: the compiler may add padding bits in the derived object, or on how method dispatching is implemented etc..)