0

I am wondering if it is safe to case one class to binary-equal class that is nevertheless not the same class.

Background: I want to do some operator-magic without "polluting" the original class (here A).

class A
{
public:
    int x;
    virtual ~A() = default;
};

class B : public A
{
public:
    B(int x) { this->x = x; }
    bool operator==(const B& b)
    {
        return x == b.x;
    }
};


    A a;
    a.x = 1;
    B* b = (B*)&a;
    *b == B(1);

This works on all my systems, but is it safe/portable to do?

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
bernd feinman
  • 324
  • 2
  • 11
  • 1
    Who guaranteed binary compatibility to you? The C++ standard surely doesn't. – StoryTeller - Unslander Monica Nov 08 '17 at 17:24
  • No, it's undefined behaviour Read about aliasing. – underscore_d Nov 08 '17 at 17:28
  • Others have said it is undefined. If you are going to do it anyway, you might want to protect yourself a bit with some static_asserts: #include static_assert(offsetof(A,x)==offsetof(B,x), "strange compiler behaviour"); static_assert(sizeof(A)==sizeof(B), "strange compiler behaviour"); static_assert(sizeof(A::x)==sizeof(B::x), "strange compiler behaviour"); – Ian Nov 08 '17 at 17:33
  • 1
    @Ian - You know, compilers do lots of things that may seem strange. But they can do them for good reasons. For instance writing specific things into padding bytes, to support various types of diagnostics. It's not that strange, once you *really* think about it. And it's something one should work with, not against. Those static assertions won't protect you, or the OP. – StoryTeller - Unslander Monica Nov 08 '17 at 17:40
  • 1
    In this instance you could define a global comparison operators `bool operator==(const A&a, const B&b);` (and/or variants taking `const A&, const A&` or `const B&, const A&`) to do this without the casting. – 1201ProgramAlarm Nov 08 '17 at 17:49
  • @1201ProgramAlarm Talk about an X/Y question! From the faulty premise that comparison with `==` requires a member `operator`, straight to a question about undefined casting hackery. – underscore_d Nov 08 '17 at 19:29

0 Answers0