3

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);
Armandas
  • 2,276
  • 1
  • 22
  • 27
  • 2
    I don't get how this have to do with strict aliasing rule. – apple apple Sep 06 '22 at 12:30
  • 3
    strict aliasing is about treating something as something it isn't. All derived classes have an `is-a` relationship with their base classes so you are allowed to take references to the bases. I don't see any glaring issues but we need an [mre] of the usage to know for sure. – NathanOliver Sep 06 '22 at 12:30
  • 1
    The two references don't even have the same address: https://godbolt.org/z/KKh9bjz5T – Alan Birtles Sep 06 '22 at 12:32
  • 4
    C++17 standard 8.2.1 "If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined", and then "a type that is a base class type of the dynamic type of the object". So of course, you are good to go. Otherwise c++ polymorphism wouldn't make sense. – pptaszni Sep 06 '22 at 12:43
  • Thanks everyone for the comments. The rule is for incompatible types, which doesn't apply in this case. – Armandas Sep 06 '22 at 13:13
  • @Armandas the types of the references are incompatible, but their addresses are different – The Dreams Wind Sep 06 '22 at 13:24
  • @TheDreamsWind Thanks. I meant to say that the reference type and the object are compatible types. – Armandas Sep 07 '22 at 04:11
  • Nitpick: there is no such thing as "pure virtual classes", only abstract classes (or ABC = abstract base classes), that is, classes with pure virtual functions, either declared or inherited. – curiousguy Feb 26 '23 at 00:27

1 Answers1

1

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.

The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49