Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ using struct arguments for functions instead of multiple arguments?

Anybody think there are advantages to using a class or struct to pass arguments ?

Like instead of

f(int,float,string)

Have

f(Args)

Where Args is struct with int,float,string members.

Advantage is easy to create multiple default parameters and not have to change function signature when new arguments added.

like image 729
steviekm3 Avatar asked Oct 13 '15 20:10

steviekm3


3 Answers

The obvious benefit would be to have logical grouping of semantically related data items.

Once you do, add some (member) operations on the structure that will guarantee your invariants.

The encapsulation raises the abstraction level of your code and this makes it easier to maintain/reason about.

See also Law Of Demeter

like image 90
sehe Avatar answered Nov 13 '22 17:11

sehe


I think the great advantage is not having to rely to parameter order. Rely on order is error prone if you are changing frequently the interface, instead if you change the parameter struct you are always explicitly assigning values to a member variable which has a specific semantic.

Take for example Direct3D11 ID3D11Device::CreateDepthStencilState function: passing a const D3D11_DEPTH_STENCIL_DESC *pDepthStencilDescis a lot more clear than asking for all the parameter it require.

Moreover think about modifiability: you don't need to change this method signature but only the underlying data structure during refactoring. I've found this especially useful when working collaboratively, where someone specify the interface and someone else have to implement it.

like image 29
Lorenzo Belli Avatar answered Nov 13 '22 17:11

Lorenzo Belli


Anybody think there are advantages to using a class or struct to pass arguments ?

Yes, I think there's a lot of advantages.

Having large parameter lists on functions will distract client code from semantical parameter consistency, which can be better managed within an appropriate struct or class.

Also it's more flexible to use a struct, if additional (possibly optional) parameters need to be added later.

like image 33
πάντα ῥεῖ Avatar answered Nov 13 '22 17:11

πάντα ῥεῖ