Thread: Passing class as Parameters

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    64

    Passing class as Parameters

    Can anyone here tell me why

    boolIsImageGreen(Image img); is computationally expensive than

    boolIsImageGreen(Image *img); which was said by the MIT Notes faster.

  2. #2
    Slime Dragoon_42's Avatar
    Join Date
    Feb 2003
    Location
    Vancouver
    Posts
    90
    Because a whole object contains more data then just a pointer to the object.

  3. #3
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    The first function requires that the Image object be copied when you make the call. The second function just makes a copy of the pointer which is inexpensive in comparison.
    bit∙hub [bit-huhb] n. A source and destination for information.

  4. #4
    Registered User
    Join Date
    Nov 2009
    Posts
    82
    A:
    When you pass an large array of data as an argument to a function every single piece of data in that argument has to be copied from one place, to another. Then that function does it's thing to the data, and gives you back a bunch of data.

    B:
    A better function would be written to perform a process on data that already exists somewhere in memory, and doesn't need to copy ALL of the *already existing data from one place to another. You do that with pointers.

    When you pass a pointer as an argument to a function, the only thing that is copied is a single value which represents a location in memory where a bunch of other data exists.

    B is faster than A because A spends a lot of *extra time copying data *unnecessarily.

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Note that this assumes that Image is expensive to copy (which for the sake of the example is probably a safe assumption).

    If Image was just a single int, then it wouldn't be faster to pass a pointer. Also, if Image used some sort of shared_ptr style internal copying, then it probably wouldn't be that different either.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. passing one class to another
    By swappo in forum C++ Programming
    Replies: 2
    Last Post: 04-19-2009, 10:35 AM
  2. Passing class member function to pthread_create
    By lehe in forum C++ Programming
    Replies: 6
    Last Post: 03-27-2009, 07:47 PM
  3. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  4. Replies: 7
    Last Post: 04-19-2006, 11:17 AM
  5. Replies: 8
    Last Post: 10-02-2005, 12:27 AM