Thread: Differene between reference object and value object

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    610

    Differene between reference object and value object

    I'm kinda confused between the two

    Code:
    #include <string>
    
    class Address;
    
    class Driver						
    {
    public:
    	Driver(Address& ad);
    
    	void SetDriverDetails(const std::string&  fname, const std::string&  lname, const std::string& IDno, 
    		const std::string&  contact);
    	const std::string&  getFName() const;
    	const std::string&  getSName() const;
    	bool ReadFromFile(std::istream& i, std::string* refNo);
    	friend std::istream& operator>>(std::istream& in, Driver& driver);
    	void SetAddress(Address add);
    	Address getAddress() const;
    	const std::string& getContact() const;
    	const std::string& getIDNo() const;
    
    private:
    	std::string firstName;
    	std::string lastName;
    	std::string idNo;
    	Address& address;
    	std::string contact;
    };
    If you look into this driver class, i have an object Address. Am kinda confused whether to make it a reference like i have, or remove the '&' sign ...

    this is how i use it
    Code:
    // Overload for reading input file streams 
    std::istream& operator>>(std::istream& in, Driver& driver)
    {
    	std::string fname, sname, licNo, contact;
    	Address add;
    	std::string IDNo;
    
    	in >> fname >> sname;
    	in >> IDNo;
    	in >> contact;
    	in >> add;
    
            // Here ....
    	driver.SetAddress(add);
    
    	driver.SetDriverDetails(fname, sname, IDNo, contact);
    	
    	return in;
    }
    
    void Driver::SetAddress(Address add)
    {
    	address = add;
    }

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    As a rule of thumb, I'll often pass a class by reference (or const reference) rather than by value.

    If your "Driver" type is smallish (eg a small number of integer members) then there is no much difference either way. If it is a moderately large type (multiple members, base classes, etc) or has a non-trivial copy constructor (eg copying it dynamically allocates memory) then you will often be better off using a reference.

    Strictly speaking, the trade-off between passing by reference or value are compiler dependent. But, in practice, the comments or rule of thumb above, usually apply.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    As a rule of thumb, I'll often pass a class by reference (or const reference) rather than by value.

    If your "Driver" type is smallish (eg a small number of integer members) then there is no much difference either way. If it is a moderately large type (multiple members, base classes, etc) or has a non-trivial copy constructor (eg copying it dynamically allocates memory) then you will often be better off using a reference.

    Strictly speaking, the trade-off between passing by reference or value are compiler dependent. But, in practice, the comments or rule of thumb above, usually apply.

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    If you can, take any non-native type by reference.
    The address inside the class should not be a reference. Why? Because:
    1) References must be initialized in the initializer list.
    2) You would be pointing that reference to a local variable.
    You need to think of the consequences.
    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
    Registered User
    Join Date
    Apr 2008
    Posts
    610
    Quote Originally Posted by Elysia View Post
    If you can, take any non-native type by reference.
    The address inside the class should not be a reference. Why? Because:
    1) References must be initialized in the initializer list.
    2) You would be pointing that reference to a local variable.
    You need to think of the consequences.
    my thoughts exactly.. i removed all references where there's no need

  6. #6
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    A reference class member works like a non-nullable const pointer; it always points to the same thing as long as a class exists. This implies that the value referred to must be in scope for the duration of the existence of the class holding the reference. This is a requirement and guarantee. When it does hold, the a reference is preferred to a const pointer, because it cannot be null. But for most cases a pointer or a copy is more useful.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  7. #7
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    You logically shouldn't have a setAddress function when the Address member in the class is a reference because you can't reseat references.
    It should be very rare to ever use a reference as a member. One of those "once in five to ten years" kind of things.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  8. #8
    Registered User
    Join Date
    Apr 2008
    Posts
    610
    Quote Originally Posted by King Mir View Post
    A reference class member works like a non-nullable const pointer; it always points to the same thing as long as a class exists. This implies that the value referred to must be in scope for the duration of the existence of the class holding the reference. This is a requirement and guarantee. When it does hold, the a reference is preferred to a const pointer, because it cannot be null. But for most cases a pointer or a copy is more useful.
    Which brings me to the next question, what's the difference between Address& add; and const Address& add; ? If you shouldn't be changing both ...

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    The way you use it in your operator>> class indicates to me that your class should contain an Address object - a driver HAS an address. Technically, you can of course have multiple drivers at the same address, but I don't think it's actually worth the extra effort of tracking addresses separately from the address.

    The function driver.setAddress() could then take a const reference - and internally copy the address to the driver's member variable.

    --
    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.

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by csonx_p View Post
    Which brings me to the next question, what's the difference between Address& add; and const Address& add; ? If you shouldn't be changing both ...
    Why is it difficult to grasp?
    If the function taking the object as argument should NOT change it and NOT store it so it can be changed later, then it should be taken as const reference.
    This only applies to references and pointers, though, since stuff passed by value are safe and won't affect 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
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    A reference cannot be set to point to another variable (only pointers can do that). For a const reference, the variable it refers to cannot be modified through the reference. For example:
    Code:
    int x = 1;
    
    int &ref = x;
    ref ++;  // increment ref and thus x
    
    const int &const_ref = x;
    // const_ref ++;  // invalid -- const_ref cannot be modified
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  12. #12
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    If we assume that the above class is correct, and SetAddress actually works as it is expected, would this:
    Code:
    // Overload for reading input file streams 
    std::istream& operator>>(std::istream& in, Driver& driver)
    {
    	std::string fname, sname, licNo, contact;
    	Address add;
    	std::string IDNo;
    
    	in >> fname >> sname;
    	in >> IDNo;
    	in >> contact;
    	in >> add;
    
            // Here ....
    	driver.SetAddress(add);
    
    	driver.SetDriverDetails(fname, sname, IDNo, contact);
    	
    	return in;
    }
    not make a reference to add [or a copy thereof depending on the parameter to SetAddress()], which is a local variable, which will disappear four lines after SetAddress call?

    I do understand that this isn't what happens - just trying to point out that you'd have to be very careful with using references that are stored in other classes.

    --
    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.

  13. #13
    Registered User
    Join Date
    Apr 2008
    Posts
    610
    I know whats the difference between a const and non-const, my code has always showed that, you guys didn't get my question !!!!

    Quote Originally Posted by King Mir View Post
    A reference class member works like a non-nullable const pointer; it always points to the same thing as long as a class exists. This implies that the value referred to must be in scope for the duration of the existence of the class holding the reference. This is a requirement and guarantee. When it does hold, the a reference is preferred to a const pointer, because it cannot be null. But for most cases a pointer or a copy is more useful.
    You logically shouldn't have a setAddress function when the Address member in the class is a reference because you can't reseat references
    Assuming he meant reset ...

    From these statements, it sound to me you can't change an address member object, unless am not reading these English statements too well. Well, English ain't my first language

  14. #14
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by csonx_p View Post
    I know whats the difference between a const and non-const, my code has always showed that, you guys didn't get my question !!!!





    Assuming he meant reset ...

    From these statements, it sound to me you can't change an address member object, unless am not reading these English statements too well. Well, English ain't my first language
    No, he meant reseat.

    I don't know what you mean by "address member object": do you mean reference (like Address &bob)? References cannot be changed to refer to other objects:
    Code:
    int foo = 5;
    int &bar = foo; //bar will always and forever refer to foo -- it can never refer to another int variable

  15. #15
    Registered User
    Join Date
    Apr 2008
    Posts
    610
    Quote Originally Posted by tabstop View Post
    No, he meant reseat.

    I don't know what you mean by "address member object": do you mean reference (like Address &bob)? References cannot be changed to refer to other objects:
    Code:
    int foo = 5;
    int &bar = foo; //bar will always and forever refer to foo -- it can never refer to another int variable
    Oh, now you making interesting comment to me here ... So in some regard, one can refer an address variable a const pointer to some degree! The differences between

    Code:
    Address& add;
    const Address& myadd;
    you can change the members of add class (setAddress(x, y, z), etc), but with myadd, you cant?? But, also you can't change add to another Address object....
    Last edited by csonx_p; 09-01-2008 at 01:19 AM.

Popular pages Recent additions subscribe to a feed