Search code examples
c++multiple-inheritancestrict-aliasing

Does taking a reference to an object via two different base classes violate strict aliasing rule?


I have three pure virtual classes, let's call them ServiceA, ServiceB and ServiceC.

The concrete implementation provides all three services using multiple inheritance:

class Concrete : public ServiceA, public ServiceB, public ServiceC
{
    //...
};

It is possible that the services could also be provided by separate concrete classes (single inheritance), so to make use of the services, I'm thinking to write a class like so:

class Consumer
{
public:
    Consumer(const ServiceA& svcA, const ServiceB& svcB);
};

If instantiate my class as shown below, will that be a violation of the strict aliasing rule?

Concrete multiService;
Consumer consumer(multiService, multiService);

Solution

  • If instantiate my class as shown below, will that be a violation of the strict aliasing rule?

    Strict aliasing rule doesn't break because svcA and svcB do not refer to the same address in the memory. When you refer to base classes, you actually refer to subobjects of the complete class Consumer, where each has its own offset (which might be more than zero), and thus different addresses even for the same instance of Consumer.