Vladimir Yanakiev
Vladimir Yanakiev

Reputation: 1310

passing interface or reference to a function as parameter

I have wrapper class and I have pass its object to a function.

class wrapper
{
/// some functionality
}

What will be better to pass as reference to the class like

fun(wrapper & ob)

or to new Interface that is inherited by wrapper like:

class Interface
{
}
 ....
class wrapper:public Interface
 ...
fun(Interface& ob)

Upvotes: 0

Views: 5007

Answers (2)

mvidelgauz
mvidelgauz

Reputation: 2214

The Interface approach is better if:

  1. You want to follow Liskov substitution principle and be able in future to replace wrapper with some other class that implements Interface
  2. You want to hide wrapper's implementation from fun's user - i.e. you won't need to #include wrapper.h before fun declaration
  3. and so on..

It is generally better to go with Interface to abstract implementation from interface, BUT also do not forget about “not pay for what you don't use” principle, i.e. if you know that you won't need any implementation of Interface other than wrapper soon enough and wrapper.h #inclusion is not a problem for your project than going with Interface will be over-design

Upvotes: 2

Peter K
Peter K

Reputation: 1382

If you want your function to only accept instances of the wrapper class, use

fun(wrapper& ob)

or

fun(const wrapper& ob)

if you do not intend to modify it.

If you want your function to accept anything that implements the Interface class (only really useful if there are more classes than just wrapper inheriting from Interface), then use:

fun(Interface& ob)

or

fun(const Interface& ob)

The choice depends on the use-case.

Upvotes: 5

Related Questions