1/6
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Objects as Function Parameters in C++
objects can be passed as arguments and returned from a function the same way we pass and return any other variable
Pass-By-Value Language
when using an object as a function parameter, we are therefore:
creating a new object instance, with identical attributes
interacting with that copy inside the function, independently of the actual variable that was passed
Why is using Objects as Function Parameters Good Behaviour?
Better performance
Better memory management
Let's data move/copies better
Pointers to Objects
when using a pointer as a function parameter we:
explicitly pass the memory location (address) of the variable by value as a parameter
dereference that pointer to access the variable's data in memory
permit reassignment of the pointer to point to a different memory location, should we wish to
References to Objects
when using a reference as a function parameter we:
create an "alias" for the same variable. The compiler treats the variable and reference as 100% equivalent
show the function will take a reference by the & symbol in the parameter list
implicitly create and dereference the reference
references never permit reassignment to a different variable, they are immutable
references must always refer to something - not permitted to be NULL
#include "Car.h"
void goOnHoliday(Car &c)
{
c.drive(1000);
}
int main()
{
Car joesPassat((char *)"White");
goOnHoliday(joesPassat);
joesPassat.show();
}
References Anywhere
We can use references anywhere we use a variable
Parameter lists
Local variables
Global variables
Class attributes
initialiser Lists
another way to initialize variables, including references, in a class constructor
a list of the values to use to initialize attributes