|
|
(1) How does c++ know to call the actual operator function? I dont see a function call in main. |
foo + bar
(2) Once the function is called, what exactly gets passed to the function as a parameter? |
foo + bar
, 'foo' is passed in as the this
object, and 'bar' is passed in as the param
parameter.foo.plus_operator( bar );
.Also, why does it get passed as an address value? |
this
pointer and the object to the right of the operator becomes the parameter. Normally you would define operator overloads as non-members, in which case you have two parameters and no this
pointer.
|
|
this
pointer come into play? If things are happening behind the scenes, can you explicitly write them out for me? Thanks.
|
|
this
is pointing to 'foo' which sent an x-argument of 3) with param.x (which is 1, and this is more-or-less obvious). This value of 4 is then assigned to temp.xthis
) value and param.y (obviously). temp
is returned because it is an object of CVector, and so after its returned it is assigned to result
and we can now use the dot separator with result
to display 'temp.x' and 'temp.y' which we calculated earlier.
|
|
friend
of the class. friend
of the class. friend
either.
15. Use const proactively. Summary const is your friend. Immutable values are easier to understand, track, and reason about, so prefer constants over variables wherever it is sensible and make const your default choice when you define a value. It's safe, it's checked at compile time, and it's integrated with C++'s type system. ... Discussion Constants simplify code because you only have to look at where the constant is defined to know its value everywhere. Consider this code:
When seeing len's definition above, you gain instant confidence about len's semantics throughout its scope (assuming the code doesn't cast away const, which it should not do). It's a snapshot of v's length at a specific point. Just by looking up one line of code, you know len's semantics over its whole scope. Without the const, len might be later modified, either directly or through an alias. Best of all, the compiler will help you ensure that this truth remains true. ... |
1. Not sure how that would change anything. |
|
|
Did you try putting that into your program and compile? |
const
after the member function parameter list. What do you think that does to the this
pointer?
|
|
1. For non-literal types, overload compound-assignment operators (like +=, -=) as member functions 2. Overload binary operators +, - etc. as non-member non-friend functions a. which take the first parameter by value b. and delegate to the appropriate compound-assignment member function |
|
|
I got the following errors message: 24:18: error: passing 'const CVector' as 'this' argument of 'CVector CVector::operator+(const CVector&)' discards qualifiers [-fpermissive] Can you elaborate a bit on what this means and why it happens? |
|
|