0

In the following lines of code, if I remove the '&' from the line ('***'), there would not be any change in the functionality apparently. Is there any reason to keep it as is or could it be useful in any case? Would you elaborate a little bit about the differences? Thanks.

#include <iostream>

class Entity
{
public:
    void Print() const
    {
        std::cout << "Hello" << std::endl;
    }

    Entity()
    {
        std::cout << "Constructed!" << std::endl;
    }
};

int main()
{
   Entity e;
   Entity* ptr = &e;
// ***
   Entity& entity = *ptr;
   entity.Print();
   std::cin.get();
}
  • 1
    `Entity& entity = *ptr;` defines `entity` as a *reference* and makes it reference what `ptr` is pointing at, which is the object `e`. It's equivalent to `Entity& entity = e;` If you had instead `Entity entity = *ptr;` would be a distinct object initialized as a *copy* of `e`. This should be clearly explained in your text-books. – Some programmer dude May 20 '21 at 04:13
  • Read https://isocpp.org/wiki/faq/references for an understanding on what '&' means and how to use it effectively. – bradgonesurfing May 20 '21 at 05:57

1 Answers1

0

You can see the difference if you actually put some state into your class and try to change it. If you copy by reference the change in the original is also seen in the copy. If you copy by value (without the & ) then a change in the original is not seen in the copy.

#include <iostream>
#include <string>

class Entity
{
public:
    std::string m_message;
    Entity(std::string msg ):m_message(msg){}

    void Print() const
    {
        std::cout << m_message << std::endl;
    }

    
};

int main()
{
   Entity e("cat");
   Entity* ptr = &e;

   // assign by reference is a bit like taking a pointer in
   // that it refers back to the original object but you
   // don't have to use '*' to dereference it. Also it is
   // not able to be null.
   Entity& byRef = *ptr;
   // assign by value creates a new object with no link to
   // the previous object
   Entity byVal = *ptr;

   byRef.Print();
   byVal.Print();

   std::cout << "========" << std::endl;
   e.m_message="dog";
   byRef.Print();
   byVal.Print();

}

which outputs

cat
cat
========
dog
cat

See https://godbolt.org/z/r4qehWxY3

bradgonesurfing
  • 30,949
  • 17
  • 114
  • 217