Friday, 20 March 2015

Passing & returning by value using the copy constructor

Passing & returning by value using the copy constructor:

The copy-constructor supports passing and returning values.

Let us see the C language how it is handling passing and returning variables by value during function calls.
See the sample  code

int MyFunction(int iVal, char chTemp);
int iResult = MyFunction(iVal1, chTemp1);

how does the compiler know how to pass and return those variables? It just knows! The range of the types it must deal with is so small – char, int, float, double, and their variations – that this information is built into the compiler.

If you figure out how to generate assembly code with your compiler and determine the statements generated by the function call to MyFunction ( ), you’ll get the equivalent of:

push chTemp1
push iVal1
call MyFunction ()
add sp,4
mov iResult, register iVal1

This code has been cleaned up significantly to make it generic; the expressions for iVal1 and chTemp1will be different depending on whether the variables are global or local.
This is also true for the expression for iResult. The appearance of the call to MyFunction ( ) will depend on your name-decoration scheme, and “register a” depends on how the CPU registers are named within your assembler.

In C and C++, the arguments are first pushed on the stack from right to left, then the function call is made.
The calling code is responsible for cleaning the arguments off the stack .But notice that to pass the arguments by value, the compiler simply pushes copies on the stack – it knows how big they are and that pushing those arguments makes accurate copies of them.

The register storage specifier holds the return value of MyFunction ( ). Again, the compiler knows everything there is to know about the return value type because that type is built into the language, so the compiler can return it by placing it in a register.

No comments: