Question

There was a question posted about inheritance and mixing interface classes:
Multiple inheritance of interfaces in C++
Which led me to this question: Does the order of inheritance influence function resolution rules?

Given:

struct Binary_Stream_Read_Intf
{
  virtual void load_from_buffer(uint8_t*& buffer_ptr) = 0;
};

struct Binary_Stream_Write_Intf
{
  virtual void store_to_buffer(uint8_t*& buffer_ptr) const = 0;
};

struct Binary_Stream_Read_Write_Intf
: public Binary_Stream_Read_Intf,
  public Binary_Stream_Write_Intf
{ ; };

struct Binary_Stream_Write_Read_Intf
: public Binary_Stream_Write_Intf,
  public Binary_Stream_Read_Intf
{ ; };

Here are my questions:

  1. Are Binary_Stream_Read_Write_Intf and Binary_Stream_Write_Read_Intf the same?
  2. Can one be substitued for the other in function calls?
  3. Can they both be used for a function requiring a Binary_Stream_Read_Intf?
Was it helpful?

Solution

1 No, they're not the same. You declared two different structs with two different names. The compiler will treat them as completely different. This is similar to saying

class Newspaper
{
    int volume;
};
class TelevisionAudioControl
{
    int volume;
};

Are these two the same? The fact that they have the same members is not enough for the compiler to consider them the same. But, in my example, since they do share the same members, you may be able to get away with explicitly casting the address of one to another:

TelevisionAudioControl tac;
Newspaper * n = (Newspaper *)&tac;

and n->volume will still work. That's more due to the magic and danger of pointers than anything else, though, and relies on how the compiler behaves, so is technically undefined behavior. And if it works at all, it only works when all members are the same and in the same order. I'm not certain that in your example, the functions will be in the same order, so I can't guarantee that you could do that bad casting magic. Since the functions are virtual, you would likely go through virtual function pointer tables, and be ok.

2 If the function is calling for Binary_Stream_Read_Write_Intf or Binary_Stream_Write_Read_Intf, then no. The compiler only accepts that class or anything inherited from it, and neither class is a descendant of the other. (You could say they're siblings, though.) However, if the function was calling for either a Binary_Stream_Write_Intf or a Binary_Stream_Read_Intf, then you can, since that's calling to a parent they both have in common. As usual, if there is no common inheritance, then you can't substitute. If the function calls for a common superclass, yes, either one will work.

3 They both inherit from Binary_Stream_Read_Intf, so yes.

OTHER TIPS

  1. No, just like struct Foo {}; and struct Bar {}; are not the same.

  2. No, see above.

  3. Yes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top