1

I have this inheritance:

class SomeClass : public s_SomeStruct {}; // where s_SomeStruct is a classic C struct.

And these declarations:

SomeClass a;
SomeClass b;
s_SomeStruct c;

I don't know why case (2) not working:

a = b; // (1) works fine
a = c; // (2) DOESN't WORK! 
c = a; // (3) Oh? It works!

Can I know why? And any simple way to cure this situation?

Thank you!

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Farah
  • 2,469
  • 5
  • 31
  • 52
  • 2
    `SomeClass` is a more specific type. The compiler can't deduce what to do with its members not in `s_SomeStruct` when doing the assignment. – The Paramagnetic Croissant Jan 06 '15 at 15:38
  • Without knowing the real problem you're trying to solve, we can't make a non-guess suggestion on how to make it do what you need. – Mark B Jan 06 '15 at 16:28

2 Answers2

1
a = c;

So, compiler would copy the base part from c. But what would it set for part specific to derived class. And when compiler is confused it just vomits.

ravi
  • 10,994
  • 1
  • 18
  • 36
1

From Liskov substituition principle:

Sub-classes should do atleast as much as the base class.

Explanation:

When inheritance takes place, all functions and variables are known to the derived clas (yes some are public, some are private and some are protected, but they are known).

While the base class does not know about the derived class.

Example, Frog is an animal, but an animal need nto necessarily be a frog.

In short, This property makes it throw the compile error

Reference:

"Derived types must be completely substitutable for their base types." - http://www.oodesign.com/liskov-s-substitution-principle.html

this says c=a is valid.

Community
  • 1
  • 1
  • Great answer, not only giving the correct explanation but also valuable background knowledge and principles – Daerst Jan 06 '15 at 16:02