Title: CS332 Midterm: Additional concepts which may be on the test
1CS332 Midterm Additional concepts which may be
on the test
2Interesting properties of Operators
- Evaluation order defined for
- Logical and operators have an interesting
property they always evaluate their operands
left to right. This alows us to use the following
simple idiom - if (ptr (ptr gt 4))
- Comma expression is evaluated left-to-right and
the value is the last term evaluated. - for (int x 0 x 1, y x - 4)
- ternary operator condition then either 2nd or
3rd operand - x lt y ? x -1
- Otherwise the operand evaluation order is not
defined. - x Arrayi Arrayi // Error
- Relational operators do not chain
- if (i lt j lt k) versus if (i lt j j lt k)
- Overloaded operators have the same precedence and
associativity as the corresponding built-in
operator. - x y ltlt 2 // x and y unsigned ints
- cout ltlt Some text\n
3More on operators
- prefix increment and decrement return the object
itself while the postfix operators return an
rvalue (i.e. non-modifiable temporary object) - int Arraycnt, ptr Array
- do ptr 0 while (ptr ! Array cnt)
- ptr 0 // OK
- int x 0
- x 0 // OK
- x 0 // Error
- Assignment operator result is the left hand
operand, and is an lValue. - It is right associative.
- Has low precedence so you may have to use parens.
- i j k 4
- if ((fd open()) lt 0)
4Function overloading Finding a match
- Overload resolution, return type is not
considered so result is not context dependent - Best match finding only one meeting all criteria
- No match not finding any matching functions
- Ambiguous more than one match is found
- The 3 steps
- Find candidates same name, visible in the
current scope - Viable functions have the same number of
parameters and the types either match or are
convertible. - Determine the best match of the viable functions
select the one with the closest matching argument
types. With multiple arguments there is a match
if - match for each argument is no worse than match
required for any other viable function and - there is at least one argument with a better
match than all other viable functions.
5Argument Type Conversions
- Ranking of conversions
- Exact match exact or trivial conversions
- no conversion
- array name to pointer
- function name to function pointer
- T to const T
- Promotion See text for a complete list
- (bool, char, short) to int -- signed and unsigned
- float to double
- double to long double
- Standard conversion see book for a complete list
- int to double
- double to int
- Derived to Base
- T to void
- int to unsigned int
- Class-type conversion user defined conversions
- match using elipses in function declaration
6Some definitions
- Translation unit (TU) what is processed by the
compiler - The one-definition rule or ODR Each class (or
enumeration, template, function etc) must be
defined exactly once in a program - it is possible to have two definitions if they
are in different TUs and are identical but it
is best to avoid this situation! - Across translation units
- Use name of functions, classes, templates,
variables, namespaces and enumerations
consistently - declare each class, , consistently. Note the
extern keyword asserts that what follows is a
declaration and not a definition. - Linkage
- eternal linkage a name that can be used in TUs
other than the one in which its is defined - internal linkage only available in the immediate
TU. - An inline function must be identically defined in
every TU in which it is used. Place in a header
or other (.i) include file. - const and typedefs by default have internal
linkage. If you want them to be global then place
in a header file.
7Classes
- Access Control
- static class members
- part of the class but not of any particular
object - referenced using class name
- define static members someplace, usually outside
of class - const member functions
- purpose is to access object data
- A non-const method can not be invoked on a const
object but a const member function can. - A class constructor has the same name as the
class - establish invariants for class
- constructors for members in initializer list are
- called before entering the constructors body
- called in order they are listed in class
declaration - Must use for reference members, consts and any
member objects without default constructors - The destructor for the member objects are called
after the objects destructor - .
8Temporary Objects
- Temporary objects may be created during the
evaluation of an expression. - it is destroyed at the end of the expression
- // s1, s2 and s3 are of type string
- const char cs (s1s2).c_str()
- cout ltlt cs
- if (strlen(cs(s2s3).c_str())lt 8 cs0
a) - do something
-
- temporary can be used to initialize a const
reference or named named object - const string s s1 s2 // const reference
- string str s1 s2 // named object
- string sx s1 s2 // error
- Another way to create a temporary object
- add_record(Student(name))
9Constructor/Destructors
- Default
- Takes no arguments
- Compiler will generate a default constructor
unless - (1) the class defines any constructors
- (2) class contains a const or reference type
- (3) class contains an object without a default
constructor - Built-in types are initialized using the same
rules as already described local scope not
initialized, global scope initialized to zero - Destructor
- Implicitly called when object is destroyed
- is not called when pointers and reference to
objects go out of scope. - However if delete is called on a pointer then the
corresponding destructor is called. - Member objects have their destructors called in
the reverse order of their declarations. - If a destructor is not defined the compiler will
synthesize one.
10Intro
class complex double re, im public complex(d
ouble r) re(r) complex(double r, double
i) re(r), im(i) complex operator(complex)
complex operator(complex) complex w(1,0),
x(2,2) complex y w.operator(x) complex z w
x
- when overloading operators the usual precedence
rules apply - obj1.operator_at_(obj2) same as obj1 _at_ obj2
- you can not define new operator tokens
- what cant be defined for user types?
- scope resolution
- . member selection
- . member selection through pointer to function
11defining operators
- binary operators can be interpreted in either of
two ways (operator _at_) either way - a.operator_at_(b) nonstatic member functions
- operator_at_(a, b) nonmember function
- if both ar edefined then overload resolution
determines which to use - Unary operators, operator _at_
- prefix
- a.operator_at_() nonstatic member function
- operator_at_(a) nonmember function
- postfix
- a.operator_at_(int) nonstatic member function
- operator_at_(a, int) nonmember function
- overload resolution
- exact match
- promotions integral promotions
- standard conversions int to double, double to
int derived to base T to void, signed to
unsigned. - user-defined conversions
- ellipses
- If two matches at same level then ambiguous
- Note return types are not considered in overload
resolution
12predefined meanings of operators
- operators , , () and -gt must be nonstatic
member functions to ensure their first operands
are lvalues. - operators , and , have predefined meanings
- enumerations are user defined types so you can
define operators - Namespaces and operator resolution
- X x Y y x _at_ y // resolving operator _at_
- if X is a class and it or a base class defines _at_
then use it - find _at_ in immediate context
- if X defined in namespace N then look there
- if Y defined in namespace M then look there
13Constructors, Conversions and Copy Control
- Copy Constructor
- If a copy constructor is not specified then the
compiler synthesizes one which uses memberwise
copy initialization. - Copy by assignment, the compiler will synthesize
an assignment operator if one is not specified.
Its semantics is also memberwise assignment. - check for self-assignment, delete old elements,
initialize and copy new elements. - Copy constructor is used for variable
initialization, argument passing, value return
and exception handling. - Note if type has a constructor then can not
initialize with list. - Single argument constructor may be called
implicitly for type conversion. - Convert from type X to type T. A conversion
operator does not take arguments and does not
specify a return type. - Class type conversions may be followed by
standard conversion when finding the best match
of candidate functions. - Only one class type conversion is applied (can
not chain them together)
14Background
- In order to take advantage of polymorphism in C
you must use either pointers or references. - The question of object ownership is critical
- Containers own the objects they contain
- copy is made on insertion
- object deleted when removed or container deleted
- Often you will use Object pointers with STL
containers - Consequences
- could make a new object each time it is
referenced - make one object, then copy its pointer
15Problems and Solutions
- context class hierarchy captures behavioral
differences - problem container is only able to store objects
of a specific type - solution store object references or addresses in
containers - context containers own contained objects
- problem objects are copied causing efficiency
problems - solution store object pointers in containers
- context object pointer appears in many
containers. - problem how do you know when it is safe to
delete object - solution reference counting
- context many references to an object that is
infrequently changed. - problem changes should only be visible to user
making the change. - solution copy-on-write semantics