SPlatten
SPlatten

Reputation: 5762

Trying to understand what is happening here with static_cast?

I'm working on an old C++ project, in the source there are two lines:

memcpy( static_cast<PLONADDRESS>(this), pa, sizeof(LONADDRESS) );
memcpy( static_cast<PLONIOFILTER)(this), pf, sizeof(LONIOFILTER) );

this is an object of type CLonFilterUnit, it is derived from public classes:

class CLonFilterUnit : public LONADDRESS, public LONIOFILTER

PLONADDRESS is:

typedef LONADDRESS* PLONADRESS;

PLONFILTER is:

typedef LONIOFILTER* PLONFILTER;

pa is of type PLONADDRESS and pf is of type PLONIOFILTER.

What I don't understand is how the same base address is used as the destination in both memcpy instructions? Is this permitted due to the way static_cast works?

Upvotes: 1

Views: 86

Answers (3)

NathanOliver
NathanOliver

Reputation: 181027

When you have a class that is derived from multiple base classes those classes can be thought of as sub objects of the derived class. You will have a base1, base2, ..., baseN part of the derived object. When you static_cast a pointer to the derived class to a pointer of one of its base classes the cast will adjust the pointer to point to the correct base (sub object) of the object. You can see that with this little example:

struct foo
{
    int a;
};

struct bar
{
    int b;
};

struct foobar : foo, bar {};

int main() {
    foobar f;
    std::cout << static_cast<foo*>(&f) << "\t" << static_cast<bar*>(&f);
}

output:

0x7ffe250056c8  0x7ffe250056cc

live example


I would also like to point out that if your class is not trivially copyable then the code has undefined behavior as memcpy requires that.

Upvotes: 3

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145429

static_cast does the necessary address adjustment.

The code (with memcpy, uppercase names, typedefs of pointers) is a great example of how to absolutely not do things. Maybe it's used as an example in a lecture series about how to lose your job quickly.

Upvotes: 0

SergeyA
SergeyA

Reputation: 62613

This is an example of some extremely dubious C++ code. I can hardly imagine why this code would be necessary - most likely, it is not.

However, to answer the question as asked, the way multiple inheritance works in C++ is by having different 'subobjects' of different base classes within the derived class. Those subobjects do not have the same address. By using static_cast on this, you select one subobject or another, and results of static_cast yield different addresses.

Upvotes: -1

Related Questions