quiz on ch - staff.tarleton.edu...although the compiler will create a default constructor for you,...

69
QUIZ on Ch.5 Why is it sometimes not a good idea to place the private part of the interface in a header file?

Upload: others

Post on 28-Jun-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZ on Ch.5

Why is it sometimes not a good idea toplace the private part of the interface in aheader file?

Page 2: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Example projects where we don’t want theimplementation visible to the client programmer:

• The library header file may show proprietary info. thatthe company doesn’t want available to competitors.

• Security (e.g. an encryption algorithm) – don’t want toexpose any clues in a header file that might help peoplecrack the code.

• Library is used in a “hostile” environment, where theprogrammers will try to directly access the privatecomponents anyway, using pointers and casting.

Page 3: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZWhy can a .cpp file be made more securethan a header file?

Page 4: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

solution

Why can a .cpp file be made more securethan a header file?

Because it can be provided in the library in analready-compiled form, so the clientprogrammers don’t have access to the sourcecode.

Page 5: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZWhat is a handle class?

Page 6: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZWhat is a handle class?

A class that is accessed only through an“opaque” pointer; the class interface anddefinition are not available to the clientprogrammer.

Page 7: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZHow is a handle class implemented in C++?

Page 8: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZHow is a handle class implemented in C++?With a forward declaration and a pointer:

Page 9: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Ch. 6: Initialization & Cleanup

Page 10: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Main ideas from chs. 4 and 5

• 4: Encapsulation (functions inside struct/class)• 5: Access control (hiding private class

members and forcing the user to access themthrough public members)

Page 11: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Two more safety issues:

A large segment of C bugs occur when the programmerforgets to initialize or clean up a variable.This is especially true with C libraries, when clientprogrammers don’t know how to initialize a struct, oreven that they must initialize it. (Libraries often do notinclude an initialization function, so the clientprogrammer is forced to initialize the struct by hand.)

text

Page 12: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Two more safety issues:C programmers are comfortable with forgetting aboutvariables once they are finished, so any cleaning upthat may be necessary for a library’s struct is oftenmissed.E.g.: What if we allocated memory dynamically for alarge array? → Memory leaks!

Page 13: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Guaranteed initialization with theconstructor

Both the Stash and Stack classes defined previouslyhave a function called initialize( ), which hints by itsname that it should be called before using the object inany other way.Unfortunately, this means the client programmer mustensure proper initialization by calling it.

text

Page 14: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Guaranteed initialization with theconstructor

In C++, initialization is too important to leave to the clientprogrammer. The class designer can guaranteeinitialization of every object by providing a specialfunction called the constructor.If a class has a constructor, the compiler automaticallycalls that constructor at the point an object is created,before client programmers can get their hands on theobject.

text

Page 15: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Name of constructor is thesame as name of class.

Note that the constructor is in thepublic section of the interface!

The constructor is a function,but it doesn’t have a return

type, not even void.

Page 16: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

What happens if we make the constructor private?

Page 17: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

It would still be possible to createobjects of this class, but we’d haveto use other member functions inTest, or friend functions.

Conclusion: The constructor shouldbe public (unless we have a goodreason to the contrary).

Page 18: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Like any member function, the first (secret)argument to the constructor is the thispointer – the address of the object forwhich it is being called.In the case of the constructor, however,this is pointing to an un-initialized block ofmemory, and it’s the job of the constructorto initialize this memory properly.

Page 19: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZ

Page 20: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Solution

Like any member function, it can also be declared and defined separately

Page 21: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Solution

Page 22: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

A constructor without arguments iscalled a default constructor.When an object is instantiated withthe default constructor, the name ofthe object (e.g. a) is provided withoutanything else, not even emptyparentheses!

Page 23: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Non-default constructor

Page 24: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZModify Exercise 1 so that the class contains an int member.

Modify the constructor so that it takes an int argument that it storesin the class member. The constructor should print out the int valueas part of its message, so you can see the objects as they are created.

Create 2 objects of this class, with different arguments passed to theconstructor.

3.

Page 25: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Solution

Page 26: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

How are constructors different fromregular member functions?

• They have the same name as the class• They have no return type• They are called automatically when

objects are declared

Page 27: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Guaranteed cleanup with thedestructor

Tilde

No returntype

Samename asthe class

No arguments!

Page 28: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

The destructor is called automaticallyby the compiler when the object goesout of scope.

You can see where the constructor gets called bythe point of definition of the object, but the onlyevidence for a destructor call is the closing braceof the scope that surrounds the object.

Page 29: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

~Tree() iscalled here

Page 30: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZ

Page 31: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Solution

Page 32: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Solution

Page 33: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZ What (if anything) is wrong with this code?

Page 34: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Solution What (if anything) is wrong with this code?

Constructors don’ttake a return type!

If the constructor has arguments,the object’s definition must

specify the same number andtypes of arguments!

It’s illegal to access privatemembers of objects!

Constructorsshould be public!

Page 35: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZHow are constructors different from regularmember functions?

Page 36: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

How are constructors different from regularmember functions?• They have the same name as the class• They have no return type• They are called automatically when

objects are declared

Solution

Page 37: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZHow are constructors and destructors:• Similar?• Different?

Page 38: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

How about structs, unions?

C++ structs and unions can have bothconstructors and destructors!

Page 39: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

[…] the destructor is still called, even when you usegoto to jump out of a scope.

You should note that a nonlocal goto, implemented bythe Standard C library functions setjmp( ) and longjmp( ),doesn’t cause destructors to be called.

For more details see https://en.wikipedia.org/wiki/Setjmp.h

Destructor nitty-gritty

Page 40: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

If the object wascreated dynamically,the destructor iscalled when thememory is deleted.

Destructor nitty-grittyNot in text

Page 41: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

To do for next time:• Read carefully all the text explanations• Redo all quizzes

EOL 1

Page 42: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Elimination of the definition blockIn C, you must always define all the variables at thebeginning of a block, after the opening brace. […] it’s“good programming style.”However:• It has always seemed inconvenient to me to pop

back to the beginning of a block every time I needa new variable.

• I find code more readable when the variabledefinition is close to its point of use.

text

Page 43: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Elimination of the definition blockIn C++, however, there’s a significant problem inbeing forced to define all objects at the beginning ofa scope:If a constructor exists, it must be called when theobject is created. However, if the constructor takesone or more initialization arguments, how do youknow you will have that initialization information atthe beginning of a scope?

text

Page 44: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You
Page 45: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Doesn’t matter whether we use braces or not – the scopeis always the entire loop, header+body. (Of course, w/o

braces, the body of the loop is only one command.)

Page 46: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZ What will this code print?

Page 47: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Solution: The scope of s is the body of the for loop(just the current iteration)

Page 48: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZ What will the code print now?

Page 49: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Solution: The scope of t is the entire for loop(header and body, all iterations, until it exits)

Destructing t

Constructing t

Page 50: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

I find small scopes an indicator of good design. Ifyou have several pages for a single function,perhaps you’re trying to do too much with thatfunction.

More granular functions are not only more useful,but they also make it easier to find bugs.

text

Page 51: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

To make sure all objects are properly initialized, thecompiler even checks to make sure that you don’tput the object definition (and thus the constructorcall) where the sequence point only conditionallypasses through it, such as in a switch statement orsomewhere a goto can jump past it.

text

Page 52: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You
Page 53: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Stash with constructors and destructors

Definitions on next slide

Page 54: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You
Page 55: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Stack with constructors & destructors

Read and understand:

Page 56: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Aggregate initialization• An aggregate is just what it sounds like: a bunch of

things clumped together. This definition includesaggregates of mixed types, like structs and classes.– An array is an aggregate of a single type.

• Initializing aggregates can be error-prone and tedious.C++ aggregate initialization makes it much safer.

Page 57: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

All these cases are identical in C and C++:

This is how we can find thearray size at run-time.

Page 58: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

?

Remember from C that any uninitialized arrayelements at the end of an initializer list are

automatically initialized with zero.

All these cases are identical in C and C++:

Page 59: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

If any of the data members are private (which is typically thecase for a well-designed class in C++), or even if everything’spublic but there’s a constructor, things are different:

Page 60: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

An example with constructorshaving multiple arguments:

Page 61: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Default constructors

Compilation error!

Compilation error!

Page 62: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You
Page 63: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

You might think that the compiler-synthesizedconstructor should do some intelligent initialization, likesetting all the memory for the object to zero. But itdoesn’t – that would add extra overhead […]

If you want the memory to be initialized to zero, youmust do it yourself by writing the default constructorexplicitly.

text

Another reason for “lazy” default constructors is that, inmany cases, it is not clear what the default value shouldbe for an object!

E.g. How should be dates initialized?

Page 64: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Although the compiler will create a defaultconstructor for you, the behavior of the compiler-synthesized constructor is rarely what you want.

You should treat this feature as a safety net, but useit sparingly. In general, you should define yourconstructors explicitly and not allow the compiler todo it for you.

text

Page 65: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZ Only one of these programs compilessuccessfully – which one and why?

Page 66: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Solu-tion

This code fails – if a constructor

exists, the compiler will not

create a default one!

Page 67: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

QUIZ How can we fix the program?

Page 68: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Write a default constructor!

Solu-tion

It’s OK to have multipleconstructors – remember

function overloading!!

But what is the use of thenon-default constructor now?

We can use it in otherdeclarations, e.g.

Bar foo(42), baz(-42);

Page 69: QUIZ on Ch - staff.tarleton.edu...Although the compiler will create a default constructor for you, the behavior of the compiler-synthesized constructor is rarely what you want. You

Individual work to do for next time:End-of-chapter exercises 4, 5, 7.

There is no homework for Ch. 6 assigned today - onehomework will be assigned for Chs.6 and 7 together.

EOL 2