what is this

Aug 26, 2016 at 4:12pm
Hi,
Regarding the following snippet I know that we are dealing with freind functions, members, classes etc., but I need help in identifying what "this" is:
(from below)

this structure is?
1
2
3
4
 void displayItem(Storage &storage)
    {
      ....this is ??
    }



context:

1
2
3
4
5
6
7
8
9
10
public:
    Display(bool displayIntFirst) { m_displayIntFirst = displayIntFirst; }
 
    void displayItem(Storage &storage)
    {
        if (m_displayIntFirst)
            std::cout << storage.m_nValue << " " << storage.m_dValue << '\n';
        else // display double first
            std::cout << storage.m_dValue << " " << storage.m_nValue << '\n';
    }
Last edited on Aug 26, 2016 at 4:17pm
Aug 26, 2016 at 4:25pm
What is odd in that member function? The by reference argument?
Aug 26, 2016 at 5:29pm
I guess an object is being passed as a parameter here?
Aug 26, 2016 at 6:06pm
A reference to an object is the parameter there.
It will avoid invoking a copy constructor and any changes made to it inside that function will alter the original object.

http://www.cplusplus.com/doc/tutorial/functions/

Edit: Addition. Passing by reference is preferred to passing by value, especially for large objects. If you do not need to modify the object, you can pass it as a const reference, ie void displayItem(const Storage &storage)

In the pass by reference-to-const and pass by pointer-to-const cases, any attempts to change the caller’s [members] within the function would be flagged by the compiler as an error at compile-time. This check is done entirely at compile-time: there is no run-time space or speed cost for the const

But as an added caveat, any functions you use that object with in that function must also be const qualified, including the object's own member functions.
https://isocpp.org/wiki/faq/const-correctness
Last edited on Aug 26, 2016 at 6:50pm
Aug 26, 2016 at 8:38pm
On the topic of const-correctness, the member function displayItem() does not seem to modify any members of this and could therefore be const.
Topic archived. No new replies allowed.