Pass object to function

This is a discussion on Pass object to function within the C++ Programming forums, part of the General Programming Boards category; Hey guys Im learning the more advanced parts of OOP slowly now and my book asks me as an exercise ...

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

    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();
    }
    I'm just trying to be a better person - My Name Is Earl

  2. #2
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,801
    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
    21,310
    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();
    }
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,411
    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,475
    Thank you so much for the examples and advice guys. That seems a much cleaner way to do things.
    I'm just trying to be a better person - My Name Is Earl

  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をこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,411
    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をこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,411
    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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21