0

I have two user-defined classes:

class A:class Base
{
type x;
doSomething();
}

class B
{
type x;
doSomething();
}

I also have a function which gets a variable of type Base and use dynamic_cast to convert it to type A and use doSomething().

class D : class Base2
{
    D(Base _base1):Base2(Base _base1)
    {
         //here is the actual problem
    }
    void foo()
    {
       //b is a private member of class Base2 of type Base
       A *a=dynamic_cast(b);
       A->doSomething();
    }
}

but I want to pass B to this function ,and at the same time I don't want B to inherit from Base.

p.s I don't have access to change Base

how is this possible?

Shohreh
  • 135
  • 9
  • You don't. See [strict aliasing](http://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule) for why. – WhozCraig Feb 13 '13 at 07:22

1 Answers1

3

Casting between unrelated classes in not safe. The safest way to achieve what I think you're trying to do is to use a function template:

template <typename T>
void foo(const T& b)
{
   b.doSomething();
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480