I am studying about when/why object slicing is dangerous.
I read a great link about what is safe slicing VS dangerous slicing.
Here is what I can summarize (roughly speaking):-
- Safe when the base type is value (e.g.
A
). - Dangerous when the base type is reference (e.g.
A&
).
After read it, I created a test code in Visual Studio + Resharper (a VS plugin).
I think my case is safe. However, I got a warning at the marked line #1
.
possibly unintended object slicing value-initialized from derived class C
class B1{ int field1=0; };
class B2{ int field2=0; };
class C: public B1,public B2{ };
class Test{
void f(B1 b){ } #2
void f2(){
C c;
f(c);
//^ possibly unintended object slicing #1
}
};
Resharper acts in a contradict way from my belief.
- Warning when the type is value.
- No warning when the type is reference (change #2 from
B1
toB1&
). - Always no warning when
C
derived from onlyB1
, no matter#2
is. (B
orB&
)
It can by summarized into a table :-
| #2=B1 | #2=B1&
==================================================
multi-inherit | warn* | no-warn*
--------------------------------------------------
inherit only from B1 | no-warn | no-warn
However, here is what I expect :-
| #2=B1 | #2=B1&
===================================================================
multi-inherit | safe* | dangerous*
-------------------------------------------------------------------
inherit only from B1 | safe | safe
Inconsistency is mark with *
.
Do I misunderstand about object slicing, or is Resharper wrong?