main: cptr = getContact();
Contact* getContact() {
Contact* cptr = new Contact;
cout << "Name: ";
cin >> cptr->m_name;
cout << "Last name: ";
cin >> cptr->m_lastname;
cout << "Phone number: ";
cin >> cptr->m_phoneNumber;
return cptr;
}
main: display(*cptr);
void display(const Contact& cptr) {
cout << cptr.m_name << " " << cptr.m_lastname << ", +" << cptr.m_phoneNumber << endl;
}
main: deallocate(cptr);
void deallocate(Contact* cptr) {
delete cptr;
}
main: setEmpty(*cptr);
void setEmpty(Contact& cptr) {
cptr.m_name[0] = '\0';
cptr.m_lastname[0] = '\0';
cptr.m_phoneNumber = 0;
}
}
Set is..
Passed parameter: receive as
* cptr | Contact& cptr
cptr | Contact* cptr
* cptr | const Contact& cptr
NULL | Contact* functionName()
what is the differences??
Contact& cptr:
Type: Reference to a Contact object.
Usage: This allows you to pass a Contact object to a function without copying it. Any changes made to cptr inside the function will affect the original Contact object.
Example: void setEmpty(Contact& cptr)
const Contact& cptr:
Type: Reference to a constant Contact object.
Usage: This allows you to pass a Contact object to a function without copying it, but you cannot modify the object through this reference. It's useful for functions that only need to read the object.
Example: void display(const Contact& cptr)
Contact* cptr:
Type: Pointer to a Contact object.
Usage: This allows you to pass the address of a Contact object to a function. You can use the pointer to access and modify the original object. You need to use the -> operator to access members of the object.
Example: void deallocate(Contact* cptr)
In summary
Reference (Contact&): Passes the object by reference, allowing modifications.
Pointer (Contact*): Passes the address of the object, allowing modifications via the pointer.
Constant Reference (const Contact&): Passes the object by reference, but does not allow modifications.