CPP Methods using Pointers

How to pass objects to Methods or functions as arguments

  • Arguments passed to a function are always done by value, which is a copy of the original.
  • If you pass an object to a function the entire object will be copied the function and if you return a object from the function entire object will be copied as well.
  • Passing an object to a function and returning one can be a very demanding process, but it depend on the object size of course.
  • A special constructor: copy constructor is called each time a temporary copy of the object is done.
  • Passing a pointer to an object as arguments to a method or function involves only the pointer in the copy. The same is true if you return a pointer reference of an object from the function.
    Example that demonstrate the cost and the difference between copy an object and copy a pointer reference to an object:
    #include <iostream>
    
    using namespace std;
    class Person
    {
    public:
      Person () {              // constructor
        cout << "Person Constructor..." << endl;
      }
      Person(Person&) {         // copy constructor
        cout << "Person Copy Constructor..." << endl;
      }
      ~Person() {              // destructor
        cout << "Person Destructor..." << endl;
      }
      // Method that passes object by value
      // and return a object by value
      Person copyObject(Person thePerson) {
      cout << "Method copyObject returning... " << endl;
      return thePerson;
      }
     // Method that passes object by pointer reference
     // and return a pointer reference of the object
      Person * refObject(Person * pPerson) {
      cout << "Method refObject returning... " << endl;
      return pPerson;
      }
    };
    
    int main()
    {
      cout << "Making a Person..." << endl;
      Person Ricard;
      cout << "Calling copyObject method ..." << endl;
      Person copyRicard=Ricard.copyObject(Ricard);
      cout << "Calling refObject method ..." << endl;
      Person * pRicard=Ricard.refObject(&Ricard);
      return 0;
    }
    When we run this application the result will be:
    Making a Person...
    Person Constructor...
    Calling copyObject method ...
    Person Copy Constructor...
    Method copyObject returning...
    Person Copy Constructor...
    Person Destructor...
    Calling refObject method ...
    Method refObject returning...
    Person Destructor...
    Person Destructor...

    You can download this example here (needed tools can be found in the right menu on this page).

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.