dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 20

Thread: pointers....

  1. #1
    Join Date
    Jan 2008
    Posts
    60

    pointers....

    whats the difference between these two?
    Code:
    	MyMouse& getMouse() {return m_mouse;};
    
    	MyMouse* getMouse() {return &m_mouse;};
    -----
    MyMouse is a class. and getMouse just returns the m_mouse which is a private member.
    -----
    I know to access the second one u need:
    m_mouse->function inside the Mymouse();
    the the first one:
    m_mouse.function inside the Mymouse();
    ----
    But when and how are they different - which is better? and when?
    Thanks in advance,

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: pointers....

    Quote Originally Posted by armen_shlang
    whats the difference between these two?
    Code:
    	MyMouse& getMouse() {return m_mouse;};
    
    	MyMouse* getMouse() {return &m_mouse;};
    -----
    MyMouse is a class. and getMouse just returns the m_mouse which is a private member.
    -----
    I know to access the second one u need:
    m_mouse->function inside the Mymouse();
    the the first one:
    m_mouse.function inside the Mymouse();
    ----
    But when and how are they different - which is better? and when?
    Thanks in advance,
    There is basically no discernable difference. One returns a reference, the other a pointer.

    The only real difference besides that is the usage of one over the other. If the m_mouse can be NULL, then you return a pointer (since references can't be NULL).

    However, you forgot the third option:
    Code:
    MyMouse getMouse() const { return m_mouse; }
    This returns a copy of m_mouse back to the caller. The reason why this may be more desirable than either of the first two choices is that the Mouse object that is returned will survive if the object that contains it is destroyed.
    Code:
    void SomeCode()
    {
         MyMouse m;
        {
           Object object;
           m = object.getMouse();
        }
        // m is still good here, even though object was destroyed
    }
    With the other two choices, this code will not work. The object that contains the mouse object is destroyed, and you will wind up with a reference that refers to nowhere, or a pointer that points to invalid memory.

    Regards,

    Paul McKenzie

  3. #3
    Join Date
    Aug 2005
    Location
    San Diego, CA
    Posts
    1,054

    Re: pointers....

    Quote Originally Posted by armen_shlang
    whats the difference between these two?
    Code:
    	MyMouse& getMouse() {return m_mouse;};
    
    	MyMouse* getMouse() {return &m_mouse;};
    -----
    MyMouse is a class. and getMouse just returns the m_mouse which is a private member.
    -----
    I know to access the second one u need:
    m_mouse->function inside the Mymouse();
    the the first one:
    m_mouse.function inside the Mymouse();
    ----
    But when and how are they different - which is better? and when?
    Thanks in advance,

    Sometimes you have to return a pointer, but my personal preference is to use references when possible. References can't be NULL like pointer variables. So if the caller gets a reference to some object, they don't have to worry about doing this:

    Code:
    if (NULL != pVariable)
    {
       pVariable->callFunction();
    }
    Even better is to return const references or const pointers, when possible. In order to use a reference, it must be assigned immediately, but pointers can be initialized to NULL and re-initialized later. You can't re-initialize references and you must initialize them to something immediately upon creation.

    Other people might have some other philosophical reasons as to why they prefer one or the other. By the way, don't fool yourself into thinking that you can return references when you should be returning by value. I think I read that somewhere (meyers, effective c++). Reference variables can be deceiving to look at because the reference variable looks and feels like any other variable but it is pointing to something that could be changed elsewhere in the program, just like a pointer.

  4. #4
    Join Date
    Oct 2004
    Posts
    296

    Re: pointers....

    Quote Originally Posted by armen_shlang
    whats the difference between these two?
    Code:
    	MyMouse& getMouse() {return m_mouse;};
    
    	MyMouse* getMouse() {return &m_mouse;};
    -----
    MyMouse is a class. and getMouse just returns the m_mouse which is a private member.
    -----
    I know to access the second one u need:
    m_mouse->function inside the Mymouse();
    the the first one:
    m_mouse.function inside the Mymouse();
    ----
    But when and how are they different - which is better? and when?
    Thanks in advance,
    A reference is very similar to a const pointer(except that a reference cannot be null). Other than that, the syntax is the major difference: you don't have to dereference a reference with that star thingy (edited).
    Last edited by 7stud; March 24th, 2008 at 09:14 PM.

  5. #5
    Join Date
    Jun 2006
    Location
    M31
    Posts
    885

    Re: pointers....

    Quote Originally Posted by 7stud
    A reference is very similar to a const pointer except that a reference always has to refer to something, i.e. it cannot refer to null. Other than that, the syntax is the major difference: you don't have to dereference a pointer.
    reference.

  6. #6
    Join Date
    Jan 2008
    Posts
    60

    Re: pointers....

    Thanks for the reply - I read more about it too.
    HOWEVER, there's one thing that confuses me. the code...
    Code:
    	MyMouse& getMouse() {return m_mouse;};
    getMouse return type is an address of the type MyMouse.
    however - the confusing part is where m_mouse is a regular variable and not the address? It makes sense if it were return &m_mouse.

  7. #7
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: pointers....

    Yes, that's one of the more confusing aspects of C++ syntax. In this case & means "reference to", not "address of".

    Generally % means reference when applied to a type or argument, and address otherwise.

    The two are related, naturally, but not quite the same.

  8. #8
    Join Date
    Jan 2008
    Posts
    60

    Re: pointers....

    Ok, I'm still confused. I though when I declared & before a function that means the return type of that specific function is an address?
    IF that's not the issue, then why use referencing?

  9. #9
    Join Date
    Dec 2006
    Posts
    166

    Re: pointers....

    Quote Originally Posted by Paul McKenzie
    since references can't be NULL
    yes they can; references can point to the same places a pointer can

  10. #10
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: pointers....

    Quote Originally Posted by armen_shlang
    Ok, I'm still confused. I though when I declared & before a function that means the return type of that specific function is an address?
    IF that's not the issue, then why use referencing?
    If you want to return an address, use a pointer (*) return type.

    What's the point of references? Well, strictly speaking there isn't one. They're just pointers in disguise. Essentially, references are pointers except that you don't have to use pointer syntax, which can make things clearer sometimes.

    The theory is that when dealing with references, you never have to worry about addresses and the like directly; you simply use an object as if it were local, but in so doing effect changes to a non-local object. With pointers, you actually have to be aware that you're dealing with an address and everything that entails.

    You're probably confused because the & operator is used when assigning the address of something to a pointer, as I said before. References are slightly different than that.

  11. #11
    Join Date
    Feb 2003
    Posts
    377

    Re: pointers....

    Quote Originally Posted by spoon!
    Quote Originally Posted by Paul McKenzie
    since references can't be NULL
    yes they can; references can point to the same places a pointer can
    In order for a reference to be null, it will have to be initialized with a null pointer that is dereferenced. Since dereferencing a null pointer is undefined behavior and a bug in the program, one can assume that the reference will never be null.

    So if your application has a reference to null, then that is merely a symptom of a bug elsewhere in the program where a null pointer was dereferenced.

    Quote Originally Posted by armen_shlang
    Ok, I'm still confused. I though when I declared & before a function that means the return type of that specific function is an address?
    No, the & before a function is part of the return type. The & when part of a type means that type is a reference.
    Last edited by jlou; March 25th, 2008 at 06:00 PM.

  12. #12
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470

    Re: pointers....

    Quote Originally Posted by jlou
    In order for a reference to be null, it will have to be initialized with a null pointer that is dereferenced. Since dereferencing a null pointer is undefined behavior and a bug in the program, once can assume that the reference will never be null.

    So if your application has a reference to null, then that is merely a symptom of a bug elsewhere in the program where a null pointer was dereferenced.
    Exactly.

    Or, to put it another way: yes, references can be NULL, but not legally.
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


  13. #13
    Join Date
    Apr 1999
    Posts
    27,449

    Re: pointers....

    Quote Originally Posted by spoon!
    yes they can; references can point to the same places a pointer can
    Set a reference to NULL, and have it not be either a hack or undefined behaviour. See 8.3.2 section 4 of the ANSI spec:
    [Note: in particular, a null reference cannot exist in a well defined
    program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bitfield.]
    This is in the same category as returning a pointer to a local variable. Sure, you can do it, but what happens when it's done?

    Regards,

    Paul McKenzie

  14. #14
    Join Date
    Jan 2008
    Posts
    60

    Re: pointers....

    Ok I'm sorry but the answers didn't digest quite well. Even though I'm sure an average person would've got it by now, but I didn't.
    So i prepared a sample code, to understand it clearly, with examples.
    Also, i'm trying to make a complete set with examples so maybe we can place it in the FAQs.

    Code:
    //**********************************************************
    //**********************************************************
    // Work In Progress
    // Author Armen Babakanian
    // A complete set of examples to illustrate the use of reference and pointers
    // in related to functions and classes
    //**********************************************************
    //**********************************************************
    
    #include <iostream>
    #include <string>
    using namespace std;
    
    //*********************************************************
    class Job
    {
    public:
    	Job(string compName, string titl, double sal)
    	: companyName(compName), title(titl), salary(sal){};
    	Job(){};
    	string& getCompanyName() {return companyName;};
    	string& getTitle() {return title;};
    	double  getSalary() {return salary;};
    	
    	void setCompanyName(string name) {companyName = name;};
    	void setTitleName(string name) {title = name;};
    	void setSalery(double name) {salary = name;};
    
    
    private:
    	string   companyName;
    	string   title;
    	double   salary; 
    };
    //*********************************************************
    class person
    {
    public:
    	person(string name, string last)
    	: m_name(name), m_last(last)
    	{
    		secondJob = new Job("DelTaco", "cleaner", 9.00);
    		fourthJob = new Job("Neverland", "cleaner", 200.00);
    	};
    	int     getAge(){return m_age;};
    	string& getName(){return m_name;};
    	string& getLast(){return m_last;};
    	void    setAge(int age) {m_age = age;};
    
    	Job& get1stJob(){ return firstJob;};
    	//------------------------------------
    	Job& get2ndJob(){ return *secondJob;};
    	//------------------------------------
    	Job* get3rdJob(){ return &thirdJob;};
    	//------------------------------------
    	Job* get4thJob(){ return fourthJob;};
    	//------------------------------------
    	Job  get5thJob(){ return fifthJob;};
    	//------------------------------------
    
    private:
    	string	m_name;
    	string	m_last;
    	int     m_age;
    	Job     firstJob;
    	Job*    secondJob;
    	Job     thirdJob;
    	Job*    fourthJob;
    	Job     fifthJob;
    };
    //**********************************************************
    void main()
    {
    	person RafaelB("Rafael","BakerMan");
    	RafaelB.setAge(22);
    	cout << RafaelB.getName() << " --" << RafaelB.getLast() << " --" << RafaelB.getAge() << endl;
    
    	RafaelB.get1stJob().setCompanyName("IBM");
    	cout << RafaelB.get1stJob().getCompanyName() << endl;
    
    	RafaelB.get3rdJob()->setCompanyName("Apple");
    	cout << RafaelB.get3rdJob()->getCompanyName() << endl;
    
    	RafaelB.get4thJob()->setCompanyName("Neverland");
    	cout << RafaelB.get4thJob()->getCompanyName() << endl;
    
    	RafaelB.get5thJob().setCompanyName("Microsoft");
    	cout << RafaelB.get5thJob().getCompanyName() << endl;
    	//this wont print Microsoft
    }
    the output is:
    Rafael --Bakerman --22
    IBM
    Apple
    Neverland

    now The Five get JOB functions w/ their private member functions are the main focus here. What exactly is happening in each one, and why is one compared to another bad or better or useful in some other way.
    Last edited by armen_shlang; March 26th, 2008 at 04:25 AM.

  15. #15
    Join Date
    Jul 2007
    Posts
    38

    Re: pointers....

    If the job object is custom for each person you could use a member object like 'firstJob' in your code. on the otherhand, if there are specific job roles in your company and several peoples can be attached to them you'll have it like

    Code:
    class Job {
         ....
         list<Job*> lst_jobs;
    };
    class person {
       ....
        Job& myFirstJob;
       Job* mySecondJob;
    }
    Here I assumed each person shoud have a firstJob, it can't be null; also you should know the firstJob at the time of constructing person objects. so it is possible to use a reference; hence use it.
    (use a member init list to initialise the reference myFirstJob)

    if the second job can be null, or you don't know the value when constructing the person, you will need to have a pointer for mySecondJob.

    to decide on how to have the getter functions,
    returning a Job obect is costly, also remember you return a copy of it, so any modification to this returned object, will not reflected in the member object.

    In my example, you can use a reference to return myFirstJob, as it can't be null. for the second job, you'll need to return a pointer.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)