CS3157: Advanced Programming: Lecture #6 June 14
CS3157: Advanced Programming: Lecture #6 June 14
Programming
Lecture #6
June 14
Shlomo Hershkop
[email protected]
1
Overview
Today:
Starting C++
Language basics: identifiers, data types, operators,
type conversions, branching and looping, program
structure
data structures: arrays, structures
pointers and references differences
I/O: writing to the screen, reading from the keyboard,
iostream library
classes: defining, scope, ctors and dtors
Bunch of code
2
Announcements
Labs
Project
Make up class
Need to makeup class, can we do this Friday ? 3 -
6pm ?
Maybe Sunday ?
Another choice
take home final and class last session….
3
Four main OOP concepts
abstraction
creation of well-defined interface for an object, separate from its
implementation
e.g., Vector in Java
e.g., key functionalities (init, add, delete, count, print) which can be
called independently of knowing how an object is implemented
encapsulation
keeping implementation details “private”, i.e., inside the implementation
hierarchy
an object is defined in terms of other objects
Composition => larger objects out of smaller ones
Inheritance => properties of smaller objects are “inherited” by larger
objects
polymorphism
use code “transparently” for all types of same class of object
i.e., “morph” one object into another object within same hierarchy
4
Main difference between c and cpp
5
Compatible
Cpp is backwards compatible with c
6
Advantages
Can create new programs faster because we can reuse
code
Easier to create new data types
Easier memory management
Programs should be less bug-prone, as it uses a stricter
syntax and type checking.
`Data hiding', the usage of data by one program part
while other program parts cannot access the data
Will whiten your teeth
7
C++ vs. Java
advantages of C++ over Java:
C++ is very powerful
C++ is very fast
C++ is much more efficient in terms of memory
compiled directly for specific machines (instead of bytecode layer, which
could also be seen as a portability advantage of Java over C++...)
8
Sample Hello.cpp
#include <iostream.h>
#include <stdio.h>
main() {
cout << "hello world\n";
cout << "hello" << " world" << endl;
}
compile using:
g++ hello.cpp -o hello
9
main()
In C main is the first thing to run
C++ allows things to run before main,
through global variables
What is the implications ?
Variable which are declared outside of
main, have global scope (will cover limits).
Can have function calls here
10
File conventions
No one convention
.C
.cc
.cp
.cpp I prefer this
.cxx
.c++
11
Keywords c++
asm private
catch protected
class public
friend this
delete throw
inline template
new try
operator virtual
12
Identifiers
i.e., valid names for variables, methods, classes, etc
just like C:
names consist of letters, digits and underscores
names cannot begin with a digit
names cannot be a C++ keyword
13
data types
simple native data types: bool, int, double, char, wchar_t
Operator overloading…
What it is
15
Type conversions
all integer math is done using int datatypes, so
all types (bool, char, short, enum) are promoted
to int before any arithmetic operations are
performed on them
17
Branching and Looping
if, if/else just like C and Java
language is block-structured
examples:
int a[5];
char b[3] = { ’a’, ’b’, ’c’ };
double c[4][5];
int *p = new int(5); // space allocated and *p set to 5
int **q = new int[10]; // space allocated and q = &q[0]
int *r = new int; // space allocated but not initialized
20
Starting
Lets talk about how functions are different
in C++
21
Defining c++ functions
a function’s “signature” is its name plus number and type of arguments
you can have multiple functions with same name, as long as the signatures
are different
example:
void foo( int a, char b );
void foo( int a, int b );
void foo( int a );
void foo( double f );
main() {
foo( 1,’x’ );
foo( 1,2 );
foo( 3 );
foo( 5.79 );
}
OVERLOADING – when function name is used by more than one function
22
C++ Function II
Foo() or Foo(void) for void arguments
Different than c
Foo(…) for unchecked parameters
Look up va_list and va_start
A cleaner approach is to pass in an array
New Trick:
Foo(int a, int b, int c=10)
Foo(4,5,2)
Foo(4,5)
23
Function III
Inline functions
Function overloading:
void foo(int a, char c)
void foo(char c)
24
Other additions
C++ includes many compiler side
additions to help the programmer (yes that
is you) to write better code
Other technical changes (will be pointing
them out as we pass them)
25
Void pointers
C allows you to assign and convert void
pointers without casting
C++ needs a cast
void * V;
..
Foo *f = (Foo)V;
26
NULL
null pointer (0)
in c, it’s a language macro:
#define NULL (void *) 0
in c++, it’s user defined because otherwise an explicit
cast is needed!
#define NULL 0
27
enums
Are treated a little differently in c++
28
Structures
struct keyword like in C (but you don’t need typedef) (last class)
example
struct point {
public:
void print() const { cout << "(" << x "," << y << ")"; }
void set( double u, double v ) { x=u; y=v; }
private:
double x, y;
}
29
Pointers and References
pointers are like C:
int *p means “pointer to int”
p = &i means p gets the address of object i. references are not like C!! they are
basically aliases – alternative names – for the values stored at the indicated
memory locations, e.g.:
int n;
int &nn = n;
double a[10];
double &last = a[9];
30
I/O Screen
// hello world in C++
#include <iostream>
using namespace std;
int main() {
cout << "hello world" << endl;
}
32
I/O keyboard
read from the keyboard using cin >>, which is like scanf() in C
example:
#include <iostream>
using namespace std;
int main() {
int i;
cout << "enter a number: ";
cin >> i;
cout << "you entered " << i <<"\n";
}
33
C++ iostream
two bit-shift operators:
<< meaning “put to” output stream (“left shift”)
>> meaning “get from” input stream (“right shift”)
34
ostream and istream
ostream
cout is an ostream, << is an operator
use cout.put( char c ) to write a single char
use cout.write( const char *p, int n ) to write n chars
use cout.flush() to flush the stream
istream
cin is an istream, >> is an operator
use cin.get( char &c ) to read a single char
use cin.get( char *s, int n, char c=’\n’ ) to read a line (inputs into string s
at most n-1 characters, up to the specified delimiter c or an EOF; a
terminating 0 is placed at the end of the input string s)
also cin.getline( char *s, int n, char c=’\n’ )
use cin.read( char *s, int n ) to read a string
35
Formatted output
in <iomanip> header file, the following are defined:
36
Example
cout << setprecision(3) << 2.34563;
37
Declaring Class
Almost like struct, the default privacy specification is private whereas
with struct, the default privacy specification is public
example
class point {
double x, y; // implicitly private
public:
void print();
void set( double u, double v );
};
38
Create some code
Lets create a simple c++ example printing
out something
Create makefile
Run it
39
Using
point x;
x.set(3,4);
x.print();
pptr->set(3,2);
pptr->print();
40
Classes: function overloading and
overriding
overloading:
when you use the same name for functions with different signatures
functions in derived class supercede any functions in base class with
the same name
overriding:
when you change the behavior of base-class function in a derived class
DON’T OVERRIDE BASE-CLASS FUNCTIONS!!
41
Access specifiers
In class declaration can have:
Public
Anyone can access
Private
Only class members and friends can access
42
Access specifiers
public
public members
can be accessed from any function
private members
can only be accessed by class’s own members
and by “friends” (see ahead)
Protected
Class members, derived, and friends.
43
Class scope
::
example:
::i // refers to external scope
point::x // refers to class scope
std::count // refers to namespace scope
44
Defining functions
void point::print(){
cout << "(" << x "," << y << ")";
}
45
Constructors and destructors
constructors are called ctors in C++
take the same name as the class in which they are defined, like in Java
46
More coding…
class point {
double x,y;
public:
point() { x=0;y=0; } // default
point( double u ) {x =u; y=0; }
// conversion
point( double u, double v )
{ x =u; y =v;}
.
.
.
}
47
usage
point p;
48
CPP pass by reference
Another way of passing by reference
int count = 10;
int &rcount = count;
49
references
void foo2(int &);
50
Variable scope
CPP allows you to specify scope through
unary scope operator (::)
So can differentiate between local and
global variables
51
code
int count = 10;
int main(){
int count = 5;
// count is local
// ::count is global
// std::count is the same as 2
52
Inline functions
What are they
53
Functions organization
You’ve programmed classes in Java
In general, what kind of functions exist
with well designed classes
54
Function types
Accessor
Mutator
Helper
Predicate
55
CPP classes
A class if a collection of functions and
variables
In CPP we have constructors and
destructors to help manage classes
56
Order of running program
In c we saw that the program always starts
from main
57
What can go wrong
The good thing about cpp is that your
program can now crash many times even
before reaching main ☺
58
Ordering and where to look for problems
Global variables
Assignments and constructors
What else ??
Main
Local variables
End local variables
End main
Global destructors
59
code
I’d like to cover a bunch of code examples now
illustrating the power of classes
60
Code simple version of point class
61
Class friends
allows two or more classes to share
private members
62
hierarchy
composition:
creating objects with other objects as members
example: array4.cpp
derivation:
defining classes by expanding other classes
like “extends” in java
example:
class SortIntArray : public IntArray {
public:
void sort();
private:
int *sortBuf;
}; // end of class SortIntArray
“base class” (IntArray) and “derived class” (SortIntArray)
derived class can only access public members of base class
63
Class derivation
encapsulation
derivation maintains encapsulation
i.e., it is better to expand IntArray and add sort() than to modify your own version
of IntArray
friendship
not the same as derivation!!
example:
is a friend of
B2 is a friend of B1
D1 is derived from B1
D2 is derived from B2
B2 has special access to private members of B1 as a friend
But D2 does not inherit this special access
nor does B2 get special access to D1 (derived from friend B1)
64
Derivation and pointer conversion
derived-class instance is treated like a base-class instance
but you can’t go the other way
example:
main() {
IntArray ia, *pia;
// base-class object and pointer
StatsIntArray sia, *psia;
// derived-class object and pointer
pia = &sia; // okay: base pointer -> derived object
psia = pia; // no: derived pointer = base pointer
psia = (StatsIntArray *)pia; // sort of okay now since:
// 1. there’s a cast
// 2. pia is really pointing to sia,
// but if it were pointing to ia, then
// this wouldn’t work (as below)
psia = (StatsIntArray *)&ia; // no: because ia isn’t a
StatsIntArray
65
danger:
don’t point a base class pointer to an array of
derived objects!
they aren’t the same size!
66
Const variables
Can have const variables in a class
67
Operator overloading
Most operators can be overloaded in cpp
Treated as functions
But its important to understand how they
really work
68
+ >>
~ &&
++
-
[]
! ()
= new
* delete
/= new[]
->
+=
>>=
<<
Look up list
69
Operators which cant be
overloaded
.
.*
::
?:
sizeof
70
X=X+Y
Need to overload
+
=
But this doesn’t overload +=
71
Functions can be member or non-member
Non-member as friends
If its member, can use this
(), [], -> or any assignments must be class
members
72
Code from fig18_03 (c book)
73
unary
Y += Z
Y.operator+=( Z )
++D
member
D.operator++()
Non member
operator++(D)
74
coding
Lets overload the point + operator
Now the =
See it in action…
75