quiz on ch - staff.tarleton.edu...although the compiler will create a default constructor for you,...
TRANSCRIPT
QUIZ on Ch.5
Why is it sometimes not a good idea toplace the private part of the interface in aheader file?
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.
QUIZWhy can a .cpp file be made more securethan a header file?
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.
QUIZWhat is a handle class?
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.
QUIZHow is a handle class implemented in C++?
QUIZHow is a handle class implemented in C++?With a forward declaration and a pointer:
Ch. 6: Initialization & Cleanup
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)
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
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!
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
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
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.
What happens if we make the constructor private?
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).
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.
QUIZ
Solution
Like any member function, it can also be declared and defined separately
Solution
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!
Non-default constructor
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.
Solution
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
Guaranteed cleanup with thedestructor
Tilde
No returntype
Samename asthe class
No arguments!
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.
~Tree() iscalled here
QUIZ
Solution
Solution
QUIZ What (if anything) is wrong with this code?
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!
QUIZHow are constructors different from regularmember functions?
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
QUIZHow are constructors and destructors:• Similar?• Different?
How about structs, unions?
C++ structs and unions can have bothconstructors and destructors!
[…] 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
If the object wascreated dynamically,the destructor iscalled when thememory is deleted.
Destructor nitty-grittyNot in text
To do for next time:• Read carefully all the text explanations• Redo all quizzes
EOL 1
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
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
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.)
QUIZ What will this code print?
Solution: The scope of s is the body of the for loop(just the current iteration)
QUIZ What will the code print now?
Solution: The scope of t is the entire for loop(header and body, all iterations, until it exits)
Destructing t
Constructing t
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
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
Stash with constructors and destructors
Definitions on next slide
Stack with constructors & destructors
Read and understand:
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.
All these cases are identical in C and C++:
This is how we can find thearray size at run-time.
?
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++:
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:
An example with constructorshaving multiple arguments:
Default constructors
Compilation error!
Compilation error!
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?
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
QUIZ Only one of these programs compilessuccessfully – which one and why?
Solu-tion
This code fails – if a constructor
exists, the compiler will not
create a default one!
QUIZ How can we fix the program?
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);
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