What is the difference (if any) between these two parameter declarations and calling methods?
#1:
void MyFunction(MyStruct& msParam)
{
.....
}
MyStruct ms;
MyFunction(ms);
And #2:
void MyFunction(MyStruct* msParam)
{
.....
}
MyStruct ms;
MyFunction(&ms);
They both seem to pass a pointer to the variable 'ms' so I'm guessing that functionally they are the same and equally efficient but is one style preferred for some occasions?
CodePudding user response:
Such a function declaration
void MyFunction(MyStruct& msParam) { ..... }
is not a valid C declaration.
It can be a valid C function declaration where the parameter means a reference to an object of the type MyStruct.
This function declaration
void MyFunction(MyStruct* msParam) { ..... }
is a valid C and C function declaration where the parameter has pointer type to an object of the type MyStruct.
So to call the function you need to apply the operator & to the passed object to get a pointer to the object.
MyStruct ms;
MyFunction(&ms);
So the functions are not the same.
The first function deals with an object of the type MyStruct
while the second function deals with the pointer type MyStruct *
.
CodePudding user response:
void MyFunction(MyStruct& msParam)
{
.....
}
The first declaration is used in C , because C is Object Oriented. So the code -
MyStruct ms; MyFunction(ms);
Refer a reference of MyStruct object.
Whereas,
void MyFunction(MyStruct* msParam)
{ ..... }
MyStruct ms;
MyFunction(&ms);
Can be used in C and C both, because here we are passing a reference and excepting pointer to MyStruct.