OOP Spring 2007 – Recitation 2 1
Object Oriented Programming
Spring 2007Recitation 2
OOP Spring 2007 – Recitation 2 2
Today:
• Function overloading• Default arguments• Constructor/destructor• References• Copy constructors
OOP Spring 2007 – Recitation 2 3
Function Overloading
OOP Spring 2007 – Recitation 2 4
Overloading• In C++ it’s possible to define several
functions with the same name, but different parameter list:
1) int pow(int b, int p);2) double pow(double b, double p);3) Complex pow(Complex b, Complex p);
• The call pow(1,2) will call function (1), while pow( Complex(2.4,7.8), Complex(1,1) ) will call function (3).
• The resolution is made at compile-time.
OOP Spring 2007 – Recitation 2 5
Call Resolution• The functions must differ in their
parameter list. The return type does not matter.
• When the compiler needs to resolve a call to an overloaded function, it:1. Finds best match for each argument
separately according to a set of rules;2. Calls the function that is the best match for
one argument and better than or equal match for all other arguments.
OOP Spring 2007 – Recitation 2 6
Ambiguities• If there are two equally good ways to make a
conversion, the compiler will refuse to choose.• It will result in compile-time error (“Ambiguous
conversion”), but only when the conversion is required:
void f(int); // No problem
void f(char); // No problem
f(3.14); // Ambiguous call
OOP Spring 2007 – Recitation 2 7
Default Arguments Values
The Way to Type Less
OOP Spring 2007 – Recitation 2 8
Why?• Imagine you have to use a function that
has 3 arguments.bool is_leap(int year, int base,
char calndr);
• 99% of the time the year is base 10 and the calendar is Gregorian.
• Calling is_leap() each time with 3 arguments is tedious.
• What if is_leap() knew default values for base and calendar?
OOP Spring 2007 – Recitation 2 9
How?• In C++ we can specify default values:
bool is_leap (int year, int base = 10,
char calndr = 'G');
• And nowis_leap(1983);is_leap(1983, 10);is_leap(1983, 10, 'G');
are all the same.• You can specify default values for all or part
of function’s arguments.
OOP Spring 2007 – Recitation 2 10
Restrictions• Once you give a default value to an
argument, you have to give a default value to all arguments that follow:
bool is_leap(int year, int base=10, char calndr);
is an error.
OOP Spring 2007 – Recitation 2 11
More Restrictions• A default value is valid only within its file.
Thus we will usually specify default values in function declarations in header files.
• A default value cannot be overridden. Thus don’t try to specify default value if a function declaration already has one (for example, if you include a header with default value for an argument).
OOP Spring 2007 – Recitation 2 12
Constructors &Destructors
OOP Spring 2007 – Recitation 2 13
Con/De-struction• When object “comes to life”, as well as
when it “dies”, some actions must be taken.
• When object is created, the class constructorconstructor is called. When object dies, the class destructordestructor is called.
• Constructor for class Car is defined by Car(parameter list). Multiple constructors are possible, differing by the parameters.
• Destructor is defined by ~Car().
OOP Spring 2007 – Recitation 2 14
C’tor - exampleClass FloatPoint {
int numer;
int denom;
Public:
FloatPoint();
FloatPoint(int n);
FloatPoint(int n,int d);
};
OOP Spring 2007 – Recitation 2 15
C’tor - exampleFloatPoint::FloatPoint(){
numer = 0;denom = 1;
}FloatPoint::FloatPoint(int n){
numer = n;denom = 1;
}FloatPoint::FloatPoint(int n,int d){
numer = n;denom = d;
}
OOP Spring 2007 – Recitation 2 16
C’tor - exampleint main()
{
FloatPoint f1(3,5);
FloatPoint f2;
floatPoint f3(2);
FloatPoint f4(f2);
FloatPoint f5();
…
}
?
OOP Spring 2007 – Recitation 2 17
C’tor - example• We could have used only one constructor
with default arguments:
FloatPoint(int n=0, int d=1);
OOP Spring 2007 – Recitation 2 18
C’tor
Static ArraysFloatPoint a[3] = {
FloatPoint(3,5),
FloatPoint(2),
FloatPoint()
};
Dynamic ArraysFloatPoint *pa;
pa = new FloatPoint[3];
Without default c’tor or c’tor with no parameters –Error!
OOP Spring 2007 – Recitation 2 19
D’tor - exampleClass String {
char* str;
Public:
String(char *s =“”);
~String();
};
OOP Spring 2007 – Recitation 2 20
D’tor - exampleString::String(char *s =“”){
str = new char[strlen(s)+1];
strcpy(str,s);
}
String::~String(){
delete[]str;
}
OOP Spring 2007 – Recitation 2 21
D’tor - exampleint main()
{
String book(“Harry Potter”);
String *hero = new String(“Harry”);
delete hero;
return 0;
}
OOP Spring 2007 – Recitation 2 22
References
The Way Around Pointers
OOP Spring 2007 – Recitation 2 23
Why?• C++ inherits C’s way of by-value
parameter passing.• Two problems:
– If you need to change the parameter inside the function, you need to pass a pointer to it.
– If you need to pass a large object, it’s better to use pointer to avoid the cost of copying.
• The function and its caller need to use pointer syntax.
OOP Spring 2007 – Recitation 2 24
A swap() With Pointersvoid SwapWithPointers(int *v1, int *v2){ int tmp = *v2; *v2 = *v1; *v1 = tmp;}
SwapWithPointers(&i, &j);
OOP Spring 2007 – Recitation 2 25
A Reference• A reference is just another name for
existing variable.• To define a reference, use & after the type.
int &a
is a reference to an int, called a.• The reference must be initialized when it
is created.int &a = j;
initializes a to be another name for j.
OOP Spring 2007 – Recitation 2 26
What Is It Exactly?• After the reference is initialized, it cannot
be changed to “refer” to another variable.• The initialization is not assignment, we
tell the compiler that a is another name for j.
• After the initialization we can use a wherever we can use j. They are different names for the same value.
OOP Spring 2007 – Recitation 2 27
How It Looksint i = 10; //
Define variable named iint &a = i; //
Define another name for iint b = i; //
Define variable named b// with
the value of ii = 5; //
i==5, a==5, b==10a = 20; // i==20,
a==20, b==10b = 0; //
i==20, a==20, b==0
OOP Spring 2007 – Recitation 2 28
Reference Parameters• We can also tell the compiler that a
function parameter is “another name” for a variable passed to it, i.e. a reference.
• Then we can change the parameter inside the function and the variable passed to it will also change.
• No copying around large objects – references are like pointers.
OOP Spring 2007 – Recitation 2 29
A swap() With References
void SwapWithReferences(int &v1, int &v2)
{ int tmp = v2; v2 = v1; v1 = tmp;}
SwapWithReferences(i, j);
OOP Spring 2007 – Recitation 2 30
Relation to Pointers• A reference is like a pointer BUT
– A reference cannot be changed to “point” to another place.
– No need for special syntax.– A reference ALWAYS needs to “point”
somewhere. There is no NULL reference.
• Side note: it’s possible to define references to pointers.
OOP Spring 2007 – Recitation 2 31
const Use• What if we don’t want to copy large
object, but also don’t want to allow changing it?
• Use const reference:void func(const string& s);
means that s is a reference for the variable passed to func(), but it cannot be changed inside func().
OOP Spring 2007 – Recitation 2 32
Copy Constructor
OOP Spring 2007 – Recitation 2 33
Copy Constructor• A constructor for class A with single
parameter of type const A& is called copy constructor.
• It is used when a parameter of type class A is passed by value (to copy the argument into the function) or when a parameter of type class A is returned by value.
OOP Spring 2007 – Recitation 2 34
inline Functions
The Way to Efficiency
OOP Spring 2007 – Recitation 2 35
Why Not #define?• We want to write short and simple function• In C you were told you can write macros for short
functions:#define max(a, b) ((a) > (b) ? (a) :
(b))
• Macros are bad:– Need to parenthesize all arguments:
#define square(x) x*xsquare(1+1)
– Strange things happen:int a=5, b=0;max(++a, b);max(++a, b+10);
OOP Spring 2007 – Recitation 2 36
Functions Are Better, But…
• Function call costs CPU time (copy arguments, create local variables, “tell” the processor to jump to another place).
• Inline functions are a compromise – it’s a way to tell a compiler to replace function call with its body.
• Simply add inline before function declaration or definition.
OOP Spring 2007 – Recitation 2 37
Works, But Not Always• The inline keyword is a hint to the compiler
to replace function call with its body:– If a function is too long, it won’t do it.– If a function is recursive, it won’t do it.– There are other cases, when inline won’t differ.
• In general, we’ll use inline if a function is two-three lines long (max(), min(), get(), set(), etc.)
OOP Spring 2007 – Recitation 2 38
Important Note• Since inline function calls should be
replaced with function’s body when we compile our code, the compiler must see the code for that function too.
• The way to do it – place inline functions in header files (.h, not .cpp, as we do with regular functions).
OOP Spring 2007 – Recitation 2 39
The New max()inline int max(int a, int b) { return a > b ? a : b;}
cout << max(5, 15) << '\n';
OOP Spring 2007 – Recitation 2 40
Another Way of Inlining• If the body of a class method is defined in
the class body, the method is implicitly inline:
class Widget {public: string name() { return _name;
}private: string _name;};
• Here name() is inline, even though we didn’t write it.
OOP Spring 2007 – Recitation 2 41
Use Inlining Judiciously• Inlining is a wonderful idea, BUT
– Increases program size (code bloat).– Complicates debugging.– Requires clients to recompile (and not relink) if
code changes.– Compilers add a lot of code into constructors
and destructors, thus inlining them is a bad idea.