Pointer and Reference in C++



Prefer pass-by-reference to pass-by-value.

  • pass-by-value increase overhead of calling copy constructor [derived> base2> base1] and destructor, this lead to reduced performance.
  • pass-by-reference remove object-slicing problem by bitwise copying.

class Person{ string firstname, lastname; }; string getFullName(Person person) { return (person.firstname+person.lastname); }
Person blogger("Viru","Rathore"); cout<<blogger.getFullName();
Person class copy constructor call 2 copy constructor for string members. string copy constructor for return by value. // very carefully select when return by reference or value destructor for both string members. destructor for person class.
Do and Don't pointer and reference uses in C++.
  1. pointer and reference should should not refer to temp objects.
    1. const char* data = Person.getName().c_str(); // return temp string object
    2. cout<<data; // temp destroyed and result will be undefined.
  2. Avoid member functions that return non-const pointers or references to members less accessible than themselves. public function should not return private or protected data member by reference or pointer.
  3. Function that returns a dereferenced pointer is a memory leak.
  4. Don't return a reference to a local object.


use default parameter or overloading:

  • default parameter : if need a single algorithm and some default value can be possible.
  • overloading : if algorithm depends on input and there is not possible default values.
  • Avoid overloading on a pointer and a numerical type.
  • void testfun(int); void testfun(stirng*); testfun(0); // always calls testfun(int)
  • Guard against potential ambiguity.


No comments:

Post a Comment

would you like it. :)