Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is object slicing on purpose a viable technique?

Tags:

c++

Suppose I have a class called AudioSample, implementation not relevant. AudioSamples can be loaded from multiple sources, for each source I derive a class from AudioSample that adds the relevant loader code for the source in question. After loading I slice the object on purpose by passing it on to the function that uses AudioSample by value.

It seems fine by me, it prevents polluting the base class with various loading functions and prevents me having to modify the (tried and tested) base class when a new loader has to be added.

However, when searching stackoverflow for object slicing I only find answers describing it as a problem and explaining it's potential pitfalls, that makes me wonder: Am I using it in a way I'n not supposed to? Will I run into potential problems by doing this I'm currently not aware off ?

like image 251
Unimportant Avatar asked Mar 19 '17 17:03

Unimportant


2 Answers

Object slicing is not a problem per se, since it's a perfectly well-defined operation. It's just that it normally raises a "WTF" moment, because it's seldom intended. My favourity metric of code quality is the reciprocal of WTFs per minute of reading, so from this perspective, it's a bad idea because it will require heavy documentation to state "yes, I really know what I'm doing."

As such, I'd be more inclined to confine it to a well-named and well-purposed function. Something like this:

class AudioSampleLoadedViaFoo : public AudioSample
{
  // ...
public:
  AudioSample getLoadedSample() const
  {
    return *this; // Slice on purpose to remove load-specific stuff
  }
};

That way, use in outside code will just see a well-defined function, with the slicing being just an implementation detail.

like image 71
Angew is no longer proud of SO Avatar answered Sep 20 '22 10:09

Angew is no longer proud of SO


for each source I derive a class from AudioSample that adds the relevant loader code for the source in question

It actually sounds like that "loader code" should not be there to begin with, or you should overload your construtor/make it more general, or you need a factory or store that "loader code" in std::function.

although slicing is defined, it is not common technique, I only fear that other developers will not understand that piece of code in the first glance, which indicates (usually) a poor code. why not write a good readable code from the first place?

Just to share how weird it is for the outside developer, would you also derive and slice std::string for every function which returns a string?

like image 25
David Haim Avatar answered Sep 22 '22 10:09

David Haim