Welcome to Introduction to Object-Oriented Programming (OOP) · QUIZ Explain the meaning of each...

Preview:

Citation preview

QUIZ

Explain the meaning of each variable declared:

• Data d, *dp = &d;

• int Data::*ptr=&Data::a;

• int (Data::*fp2) (float);

• int (Foo::*fptr) (string);

• int (Foo::*fptr) (string) = &Foo::f;

QUIZ

Explain from context the meaning of foo, bar, baz and qux in the following code:

• (foo.*bar)(42, 43);

• float f = (baz->*qux)();

• foo.*bar = 42;

• baz->*qux = 43.5;

QUIZ The following class exists in a program:

class A{

public:

int m;

int n;

};

Declare and initialize a pointer to each of its members.

QUIZ The following class exists in a program:

class A{

public:

int m;

int n;

};

int A::*pm_m = &A::m;

int A::*pm_n = &A::n;

QUIZ

Instantiate two objects of class A, x and y. Use the pointers to set the following values for their members: • x: 1, 2 • y: 3, 4

class A{

public:

int m;

int n;

};

int A::*pm_m = &A::m;

int A::*pm_n = &A::n;

QUIZ class A{

public:

int m;

int n;

};

int A::*pm_m = &A::m;

int A::*pm_n = &A::n;

A x, y; x.*pm_m = 1; x.*pm_n = 2; y.*pm_m = 3; y.*pm_n = 4;

QUIZ class A{

public:

int m;

int n;

};

Declare a public member function add() that returns the sum of the two data members.

Declare and initialize a pointer to add().

A x;

QUIZ class A{

public:

int m;

int n;

int add(){return m+n;}

};

Use the pointer to display the sum of the two members of x.

A x; int (A::*fp)(); fp = &A::add;

QUIZ class A{

public:

int m;

int n;

int add(){return m+n;}

};

A x; int (A::*fp)(); fp = &A::add; cout <<(x.*fp)();

Ch. 12: Operator Overloading

Operator overloading is just “syntactic sugar,” i.e. another way to make a function call:

shift_left(42, 3); 42 << 3; The difference is that the arguments for this function don’t appear inside parentheses, but instead they surround or are next to the operator’s character(s).

example

Let’s first understand what we’re trying to do!

Just a “wrapper” for the int type!

Wait a second! Isn’t + a binary operator?

Yes, but, when defined as member function, the LEFT operand is always the object, so only the RIGHT operand needs to be passed.

Why is the return value const?

In order to prevent “crazy” uses like (x + y) = z;

Write the member function to overload the division / operator.

QUIZ

Must #include <cassert>

Note: The author of the text has his own, customized version of assert, called require:

…..

Now let’s overload the compound assignment operator +=

. . .

Why non-const and why reference?

. . .

Non-const to prevent uses like (x += y) += z;

Reference to prevent the creation of a copy.

. . .

If this is a pointer to the current object, *this is …

Overloadable operators Although you can overload almost all the operators available in C, the use of operator overloading is fairly restrictive:

• cannot combine operators that currently have no meaning in C (such as ** to represent exponentiation)

• cannot change the evaluation precedence of operators

• cannot change the number of arguments required by an operator.

Unary operators

. . .

declarations

. . .

definitions

Examples with member functions

. . .

Thoroughly read and understand the entire subsection Unary operators, including Increment and Decrement.

We stop before the subsection

Binary operators

Individual work for next time:

End-of-chapter exercises 1, 2, 3

EOL 30

Based on their “signatures” (i.e. function headers), explain what the compiler does when it encounters each operator.

QUIZ

What is this operator called?

When the compiler sees ++a (a pre-increment), it generates a call to operator++(a); but when it sees a++, it generates a call to operator++(a, int). That is, it differentiates between the two forms by making calls to different overloaded functions.

QUIZ

Why does Integer have to “befriend” all these functions?

QUIZ

. . . .

B/c they’re global functions, and the member is private.

QUIZ

. . . .

Binary operators Assignment can only be implemented as member function (not global!), that’s why we have it only in the Byte class:

?

More in the separate section Overloading assignment

Binary operators

More of the same …

Read this section!

1.If you only need to read from the argument and not change it, default to passing it as a const reference.

• Ordinary arithmetic operations (like + and –, etc.) and Booleans will not change their arguments, so pass by const reference is predominantly what you’ll use.

• When the function is a class member, this translates to making it a const member function.

Arguments & return values - GUIDELINES -

1.If you only need to read from the argument and not change it, default to passing it as a const reference.

• Only with the operator-assignments (like +=) and the operator=, which change the left-hand argument, is the left argument not a constant, but it’s still passed in as an address because it will be changed.

Arguments & return values - GUIDELINES -

2. The type of return value you should select depends on the expected meaning of the operator.

• If the effect of the operator is to produce a new value, you will need to generate a new object as the return value. For example, Integer::operator+ must produce an Integer object that is the sum of the operands. This object is returned by value as a const, so the result cannot be modified as an lvalue.

Arguments & return values - GUIDELINES -

Arguments & return values

3. All the assignment operators modify the lvalue. To allow the result of the assignment to be used in chained expressions, like a=b=c, it’s expected that you will return a reference to that same lvalue that was just modified.

• But should this reference be a const or nonconst? Although you read a=b=c from left to right, the compiler parses it from right to left, so you’re not forced to return a nonconst to support assignment chaining.

- GUIDELINES -

Assignment is right-associative

What is the output?

QUIZ

It’s the same as if parenthesized

thus:

QUIZ

3. All the assignment operators modify the lvalue. To allow the result of the assignment to be used in chained expressions, like a=b=c, it’s expected that you will return a reference to that same lvalue that was just modified.

• However, people do sometimes expect to be able to perform an operation on the thing that was just assigned to, such as (a=b).func( ); to call func( ) on a after assigning b to it. Thus, the return value for all of the assignment operators should be a nonconst reference to the lvalue.

Arguments & return values - GUIDELINES -

vs.

Returning a temporary a.k.a. the return value optimization

The compiler builds the object directly into the location of the outside return value. Only constructor is called. No copy-constructor is called! No destructor is called (no object in this function’s scope – leave it to the caller’s scope!)

Constructor, copy-constructor, and destructor are called.

Read over lightly:

operator[]

new

delete

operator,

Operator->

Generally used when you want to make an object appear to be a pointer.

Since such an object has more “smarts” built into it than exist for a typical pointer, an object like this is often called a smart pointer.

Operator->

Especially useful if you want to:

• “wrap” a class around a pointer to make it safe

• create an iterator (object that moves through a collection /container of other objects and selects them one at a time, without providing direct access to the implementation of the container)

Operator->

A pointer dereference operator must:

• be a member function

• return an object (or reference to an object) that also has a pointer dereference operator, or

• return a pointer that can be used to select what the pointer dereference operator arrow is pointing at.

example

It’s more common to see a “smart pointer” or “iterator” class nested within

the class that it services – see the next example NestedSmartPointer.cpp

. . . . . Member function of

the vector class

nullptr

Abort at the end of container

Let’s understand this! sp is an object of class SmartPointer …

(next slide)

Shouldn’t it be sp -> -> f() instead?

Shouldn’t it be sp -> -> f() instead?

A: Yes, technically it should, but the compiler is built to automatically do the work of the second -> operator.

We stop before the subsection

Operators you can’t overload

EOL 31

Operators you can’t overload

• The member selection operator.

• The pointer to member dereference operator.*

• There’s no exponentiation operator. The most popular choice for this was operator** from Fortran, but this raised difficult parsing questions. Also, C has no exponentiation operator, so C++ didn’t seem to need one either because you can always perform a function call.

• There are no user-defined operators.

• You can’t change the precedence rules.

Non-member operators

If it doesn’t make any difference whether we overload the operators with member or global functions, it is recommended to choose members; this emphasizes the association between the operator and its class.

Non-member operators

However, sometimes you want the left-hand operand to be an object of some other class.

A common application is when the operators << and >> are overloaded for iostreams; we want to be able to write:

MyClass myObject;

cout <<myObject;

cin >>myObject;

These are global functions, not members!

Remember stringstream from Lab 7!

Overloading assignment

In which of these commands is the copy-constructor called?

Hint: (Only) when a new object is created from an existing object!

The right-hand side does not even need to be a user-defined object:

Assignment syntax

Constructor syntax (recommened!)

Conclusion: Any time you’re initializing an object using an = instead of the ordinary function-call form of the constructor, the compiler will look for a constructor that accepts whatever is on the right-hand side.

One simple rule: copy all of the necessary information from the right-hand object into the current object (that is, the object that operator= is being called for)

Common mistake: you should always check first for self-assignment!

In some cases, such as this one, it’s harmless if you perform the assignment operations anyway, but if changes are made to the implementation of the class, it can make a difference, and if you don’t do it as a matter of habit, you may forget and cause hard-to-find bugs.

Pointers in classes

Problem: Simply copying a pointer means that you’ll end up with two objects pointing to the same storage location.

Solution: You need to do bookkeeping of your own.

example

Simply copy whatever the pointer refers to. (Also works for copy-

construction.)

Problem with the copy technique

If the object requires a lot of memory or time for initialization, copying is not efficient.

Solution: next slide

Reference counting

You give intelligence to the object that’s being pointed to so it knows how many objects are pointing to it.

Both copy-construction and assignment mean: attaching another pointer to an existing object and incrementing the reference count.

Destruction means: decrementing the reference count. If the reference count goes to zero, destroy the object!

The program

C12:ReferenceCounting.cpp

is not required for the exam.

Read FYI.

Automatic operator= creation

Because assigning an object to another object of the same type is an activity most people expect to be possible, the compiler will automatically create a type::operator=(type) if you don’t make one.

The behavior of this operator mimics that of the automatically created copy-constructor; if the class contains objects (or is inherited from another class), the operator= for those objects is called recursively, a.k.a. memberwise assignment.

Remember from ch.11: “Deleted” functions were introduced in

C++11

We stop before the section

Automatic type conversion

SKIP the remainder of ch.12

Homework for ch. 12

Provided as separate handout (also available on our webpage --> agapie.net)

Due Friday, Nov. 20, at the beginning of class.

Please hand in a hard-copy, do not email!

EOL 32

Recommended