Pergunta

I have this code which I CANNOT change:

A.h

 class B;
 class A
{
  A();
  void * getB();
  private:
  B * b;
}

A.cxx

namespace
{
    class B : public QTabWidget
    {
        foo()
        {
         ...
        }
        bar()
        {
         ...
        }
    }
}
A::A()
{
    b = new B();
}
A::getB()
{
    return b;
}

I want to access b and it's methods (foo or bar or inherited methods ) in a class which inherits A. Can I do that?

C.h

class C : public A
{
  C();
  private:
  D * d;
}

C.cxx

namespace
{
    class D : public QTabWidget //Exact copy of class B
    {
        foo()
        {
        ... 
        }
        bar()
        {
        ...
        }
    }
}
C::C()
{
    d = (D*) getB();
    d.foo()
    d.bar()
}

Is it safe? Is it allowed? I've tried it and it seems to work. If it is safe, can I extend D with more static methods, or Methods, or even attributes?

Foi útil?

Solução

No, it's not safe.

In theory, you may be able to make it work, as long as the first part of D is identical to B. You could probably append new things to D as well.

In practice though, it's usually a very bad idea. You're relying on manually keeping the classes in sync with each other. More importantly, you're relying on the compiler handling both classes in exactly the same way, which may depend on various configuration options (e.g. packing).

If you make the slightest mistake then you will get undefined behaviour, because the program could end up accessing or executing something arbitrary. Crucially, it might seem to work for a while, and then suddenly break unexpectedly in any number of ways. That kind of problem can be very hard to track down because you're deliberately bypassing the compiler's type checking.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top