Reputation: 1310
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
Reputation: 2214
The Interface
approach is better if:
wrapper
with some other class that implements Interface
wrapper
's implementation from fun
's user - i.e. you won't need to #include wrapper.h
before fun
declarationIt 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
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