0

Normally it has no sense and is very unsafe, but only theoretically if there is a way,

Here is example:

#include<iostream>

struct A {
    uint32_t &get() {
        return *reinterpret_cast<uint32_t *>(this);
    }

    void set(const uint32_t val) {
        *this = *reinterpret_cast<const A *>(&val);
    }
};

struct B : A {
    uint16_t a;
    uint16_t b;

    void set_b(const uint32_t val) {
        *this = *reinterpret_cast<const B *>(&val);
    }
};

main() {
    B k;
    k.a = 0x1234;
    k.b = 0x5678;
    std::cout << std::hex << k.get() << " : " << k.a << " " << k.b << std::endl;
    k.set_b(0x87654321);
    std::cout << std::hex << k.get() << " : " << k.a << " " << k.b << std::endl;
    k.set(0xaabbccdd);
    std::cout << std::hex << k.get() << " : " << k.a << " " << k.b << std::endl;
}

I get this result:

56781234 : 1234 5678
87654321 : 4321 8765
87654321 : 4321 8765

But I except that last should be:

aabbccdd : ccdd aabb

So, why overwriting data in structure from parent not working?

Experiment:

I make one experiment, that I add one variable into struct A, then set function was working as expected (but final structure was bigger)

Of course there exists different ways how to deal with this (for example with unions) but I only playing with this and I interested why this is not working.

Community
  • 1
  • 1
vlk
  • 2,581
  • 3
  • 31
  • 35
  • 1
    the result you get depends on endianess and your code has multiple undefined behavior – Tyker Jul 17 '18 at 08:27

1 Answers1

5

In the class A the set function is really

void set(const uint32_t val) {
    (*this).operator=(*reinterpret_cast<const A *>(&val));
}

That will invoke the automatically generated A::operator= function. But since A doesn't have any member variables to be copied, it does nothing.


And now that you've done your experiment, please don't do anything like that ever again.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • So, this mean that if struct has no member variables, then it is not a struct? something like namespace only ? – vlk Jul 17 '18 at 08:54
  • @vlk Not quite like a namespace, since the member functions are not `static`, and you can not add members to the structure like you can with a namespace. A `struct` is still a `struct` that can (if you don't explicitly prevent it with a deleted constructor or some such) be instantiated as an object. – Some programmer dude Jul 17 '18 at 09:00
  • @vlk Of course it is a `struct`. As long as you use the keyword `struct`, then it is a `struct` (or in C++ you may call it `class`). The only thing that is exceptional is that trivial methods do nothing. And sometimes an "empty struct" is useful, such as in SFINAE technology. – con ko Jul 17 '18 at 09:01