0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Differences parameter types in C++

Posted at
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.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?