Reputation: 295
Lets say we had a type struct called Animal and we had two objects called Cat and Dog. I am trying to write a code that declares an object, named Cat and initializes its data members to be the same value as those of another object named Dog. Both objects are of type struct Animal.
I was wondering if it was Animal Cat = Dog
. or
Animal Cat = &Dog
.
I was wondering what the difference was too.
Upvotes: 0
Views: 51
Reputation: 16777
Both those statements are examples of copy initialization. The constructor matching the type of the expression on the rhs of the equals is what gets picked. So, your question really is about how to pass arguments to a function accepting them by reference. The answer is that it looks exactly like it would if you are passing by value. The &
Prefix takes the address of the variable and is used when you are passing a pointer to the function. So, if your Animal
had a constructor like this Animal::Animal(Animal*)
, it would be picked by the call Animal Cat = &Dog
.
Upvotes: 0
Reputation: 395
You're right in your first attempt. A variant can be seen here:
Animal cat("silvester");
Animal dog("fido");
cat = dog;
In your second example, you're actually taking the address of "Dog," and assigning it to a non-pointer type (Animal). The second version won't compile, because the types don't match.
The difference is huge. We're talking about objects, and pointers to objects. The value of a pointer is an address in memory, while the value of an object is the object's data itself.
Upvotes: 3