I just have one question, when you have a class that is defined:

class box{
public:
         int *value;
         box()
         {
                   value=new int;
                   *value=0;
          };
          box(box &c)
          {*value=*c.value;};
};

If in the main you said class box b(a); it would work as expected. But I don't understand how that makes sense. How can you set the adress of the object to another object. It would make sense to set it to another object's adress. Or is it that the reference operator is being used differenly than as an adress getter?

Recommended Answers

All 5 Replies

line 10 is wrong. Why is value a pointer? From the class constructure it appears to be just a single integer, and you don't need a pointer for that

And get rid of those stars on line 10.

class box{
public:
         int value;
         box()
         {
                   value=0;
          };
          box(box &c)
          {value=c.value;};
};

Sorry I was working on complex copies when I screwed line 10 up, but what my real focus was was:

If in the main you said class box b(a); it would work as expected. But I don't understand how that makes sense. How can you set the adress of the object to another object. It would make sense to set it to another object's adress. Or is it that the reference operator is being used differenly than as an adress getter?

You're right, it is being used differently. In this case, it is passing the object by reference, which is just C++'s shortcut around pointers. It just means anything you do to the parameter within the method will be permanent.

so this is a totally different use of the & operator that I was not aware of? Or is this use of the & operator used in that case only, with objects in functions?

The & operator is used to pass variables by reference when in the parameter list of a function. Outside of that context it is always used to get the address of a variable. Othere than this, I am not what you are asking.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.