Thread: Pass object to function

  1. #1
    Its hard... But im here swgh's Avatar
    Join Date
    Apr 2005
    Location
    England
    Posts
    1,688

    Pass object to function

    Hey guys

    Im learning the more advanced parts of OOP slowly now and my book asks me as an exercise to pass a class object to another function then show its value.

    I have done so, as shown below, but I am no happy with the way my book says not to use references when passing objects. Do you think I should look up passing an object by reference instead? I am ok with pointers and references, but nowhere in my book does it explain how to pass an object by reference using '&'.

    Here is my answer for the exercise, It does work but I feel what I have done is unsafe.

    Code:
    #include <iostream>
    
    class NumberTeller
    {
    public:
       NumberTeller() { setNumber(); }
       ~NumberTeller() {}
           
       void setNumber() { int number = 5; m_Number = number; }
       int getNumber() const { return m_Number; }
           
    private:
       int m_Number;
    };
    
    void showNumber ( NumberTeller *nm );
    
    int main()
    {
        NumberTeller *nm = new NumberTeller;
        
        showNumber ( nm );
        
        delete nm;
        nm = NULL;
        
        std::cin.get();
        
        return 0;
    }
    
    void showNumber ( NumberTeller *nm )
    {
       std::cout << "Value of number: " << nm->getNumber();
    }
    Double Helix STL

  2. #2
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    Why would your book tell you not to pass objects by reference. There is nothing wrong with that.

    Example Reference Code:
    Code:
    #include <iostream>
    using std::cout;
    
    class CObject
    {
    public:
    	CObject()
    	{
    		mValue = -1;
    	}
    
    	void SetValue(const int value)
    	{
    		mValue = value;
    	}
    
    	const int GetValue() const
    	{
    		return mValue;
    	}
    private:
    	int mValue;
    }
    
    int main(void)
    {
    	CObject instance;
    	
    	cout<<instance.GetValue();
    
            //You don't have to pass the value a special way.
    	passObjectFunction(instance);
    
    	cout<<instance.GetValue();
    }
    
    //This is a function that accepts a reference.
    void passObjectFunction(CObject &instance)
    {
    	instance.SetValue(20);
    }
    Woop?

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    I have done so, as shown below, but I am no happy with the way my book says not to use references when passing objects.
    So am I. What book is that?

    Do you think I should look up passing an object by reference instead?
    Yes, since it makes more sense in this case, especially since dynamic memory allocation is not necessary here.

    It does work but I feel what I have done is unsafe.
    I do not think it is unsafe. The setNumber() function is rather strange though, since typically you would take the new value as an argument. You might also use an initialisation list in the constructor instead.

    As an example of eliminating dynamic memory allocation and using pass by reference:
    Code:
    void showNumber ( const NumberTeller& nm );
    
    int main()
    {
        NumberTeller nm;
        
        showNumber ( nm );
        
        std::cin.get();
        
        return 0;
    }
    
    void showNumber ( const NumberTeller& nm )
    {
        std::cout << "Value of number: " << nm.getNumber();
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    The beauty of references is that you only need to tell the compiler it's a reference in the argument list. Then you can use it as if you passed it by value.
    I also find it quite silly that it would tell you to pass the object by value. When it comes to objects, I always pass them by const reference (if there's no need to modify them).
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    Its hard... But im here swgh's Avatar
    Join Date
    Apr 2005
    Location
    England
    Posts
    1,688
    Thank you so much for the examples and advice guys. That seems a much cleaner way to do things.
    Double Helix STL

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Yes, references is what you should use for these sort of things.

    I can't understand why a book would suggest otherwise - there's no sane reason for that. Internally (when the compiler done it's job) both are identical, but there's stricter rules about references, and the syntax is easier. The only point about using references that I don't like is that the reference isn't visible in the calling code, so you can't see that it's a reference.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    Banned
    Join Date
    Nov 2007
    Posts
    678
    Quote Originally Posted by Elysia View Post
    The beauty of references is that you only need to tell the compiler it's a reference in the argument list. Then you can use it as if you passed it by value.
    The ugly part is when you have to declare reference to a pointer

    I also find it quite silly that it would tell you to pass the object by value. When it comes to objects, I always pass them by const reference (if there's no need to modify them).
    - Avoid passing local objects by reference, especially when the caller exits before the callee.
    - The object is static and you want a new copy to pass and not the static object which can be overwritten on a later function call.

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by manav View Post
    The ugly part is when you have to declare reference to a pointer
    Not necessarily:
    Code:
    void foo(int*& mypointer)
    - Avoid passing local objects by reference, especially when the caller exits before the callee.
    I think that one is a sin not related to references. Same thing happens when you pass it by pointer, as well.

    - The object is static and you want a new copy to pass and not the static object which can be overwritten on a later function call.
    It can't be overwritten if you pass it as const.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  9. #9
    Banned
    Join Date
    Nov 2007
    Posts
    678
    Quote Originally Posted by Elysia View Post
    Not necessarily:
    Code:
    void foo(int*& mypointer)
    I meant confusing.
    Code:
    int*p or int *p // which is correct?
    int *p, *q or int* p, q // now? which is correct?
    now:
    why int*& p and why not int &*p, &*q // ???
    I think that one is a sin not related to references. Same thing happens when you pass it by pointer, as well.
    I was citing example when not to pass by reference. Of course you are right too.

    It can't be overwritten if you pass it as const.
    Dang!
    I meant something like this:
    Code:
    void f(int i) {
      static Foo obj;
      obj.i = i;
      byRef(obj);
      obj.i *= 2; // The passed reference is also changed?
    }

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Now sure what you're getting at with some of them, but...
    Code:
    int*p or int *p // which is correct?
    Both are pointers of type int*.
    (This is also why I like int* p)

    int *p, *q or int* p, q // now? which is correct?
    p and q are pointers of type int*
    And the second, only p is a pointer to int*, q is only an int.
    (On a side note, this is why I always define pointers on separate lines.)

    Code:
    why int*& p and why not int &*p, &*q // ???
    The first is easy:
    A reference is a link to a type. So if you want a reference to something, first you type the type, then the reference sign, so to make a reference to a pointer, write the type of the pointer first, in this case, int*, and then write a &, so it becomes int*&.
    As for the second, put all of them on separate lines and it will not become confusing anymore.

    Dang!
    I meant something like this:
    Code:
    void f(int i) {
      static Foo obj;
      obj.i = i;
      byRef(obj);
      obj.i *= 2; // The passed reference is also changed?
    }
    Yes, the reference is also changed because it's a link to the original value which you just changed.
    But usually the purpose of passing a reference in this circumstance (assuming it's const) is so that the function should be able to track any changes made to the original value. The function can, for example, signal another function to do a different behaviour.
    If it's passed by non-const, then it's usually that the function you pass it to wants to change the original variable.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    swgh, maybe references are covered later in your book?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Speed test result
    By audinue in forum C Programming
    Replies: 4
    Last Post: 07-07-2008, 05:18 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. How to pass member functions into a function object...
    By TeenWolf in forum C++ Programming
    Replies: 3
    Last Post: 04-24-2007, 01:01 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. A question about constructors...
    By Wolve in forum C++ Programming
    Replies: 9
    Last Post: 05-04-2005, 04:24 PM