c review
TRANSCRIPT
C/C++ Review
1
1. 기본적 자료형
기본적인 자료형 (Data Type)
변수 (variable): 자료를 저장하는 기억장소 - 모든 변수는 자료형이 지정되어 있어야 하고 , 한번 지정된 자료형은 변할 수
없다 . - 변수를 사용하기 전에 변수를 미리 정의해야 한다 . 자료형 _ 이름 변수리스트 ; 자료형 _ 이름 : 정수형 : int, short int, long, unsigned int, … 실수형 : float, double, … 문자형 : char 부울형 : bool, …• 연산자 sizeof - 자료형의 크기 예 sizeof(int)
변수의 이름에 대한규칙
– 중복된 이름의 변수를 사용할 수 없다 .– 변수 이름에는 알파벳 , 숫자 , 언더스코어 (_) 만 포함할 수 있다 .– 단 , 숫자는 변수 이름의 첫 번째 글자로 사용할 수 없다 .– 변수 이름의 길이에는 제한이 없다 .– 변수 이름에 포함하는 알파벳은 대소문자를 구분한다 .– 키워드는 변수의 이름으로 사용할 수 없다 .
변수의 이름을 붙일 경우
– 변수의 용도에 맞는 이름 예 : StudentsNumber
– 변수내의 단어와 단어는 구분 예 : StudentsNumber, student_number
– 필요 없이 긴 이름은 피함
자료형의 종류• C++ 에서 제공하는 기본 타입들
정수 타입 (Integers)• 정수 타입별로 보관할 수 있는 값의 범위
• 10 진수 , 8 진수 , 16 진수의 표현
타입 최소값 최대값 크기(bytes)
signed short -32768 32767 2
unsigned short 0 65535 2
signed int -2147483648 2147483647
4
unsigned int 0 4294967295
4
signed long -2147483648 2147483647
4
unsigned long 0 4294967295
4
* 32 비트 윈도우즈 시스템을 기준으로 한 값
int decimal = 41; // 10 진수int octal = 041; // 8 진수int hexadecimal = 0x41; // 16 진수
실수 타입 (Floating points)
• 실수 타입별로 보관할 수 있는 값의 범위
타입 최소값 최대값 크기(bytes)
float 1.17549E-38 3.40282E+38 4
double 2.22507E-308 1.79769E+308
8
long double 2.22507E-308 1.79769E+308
8* 32 비트 윈도우즈 시스템을 기준으로 한 값
문자 타입 (Characters)
• 문자 타입별로 보관할 수 있는 값의 범위
• 문자 타입도 결국은 숫자를 보관한다 .
타입 최소값 최대값 크기(bytes)
signed char -128 127 1
unsigned char 0 255 1
wchar_t 0 65539 2* 32 비트 윈도우즈 시스템을 기준으로 한 값
부울 타입 (Boolean)
• 부울 타입은 true 혹은 false 의 값을 갖는다 .
bool b1;bool b2;
b1 = true;b2 = false;
cout << “b1 = “ << b1 << “\n”;cout << “b2 = “ << b2 << “\n”;
형 변환
• 내부적 형 변환암시적 형변환은 변수에 대한 처리 과정에서 자동적으로 발생하는
형변환이다 . 이 때 값이 변할 수 있다 . 예 : 실수 타입에서 정수 타입으로 형변환
발생 시 소수점 이하 부분이 잘린다 . ( 반올림 아님 )
• 강제 형 변환 1) (type) expression 예 float f = 66.89; int i = (int)f; // i 는 66 이 된다 . 2) static_cast < 자료형 이름 >( 수식 ) 예 : int n = static_cast<int>(y+0.5);
상수
• Define - 매크로 예 ) #define pi 3.14
• const 자료형이름 상수이름 = 초기값 ; 예 ) const double pi = 3.14;
연산자• 산술연산자 => 산술식 +. -, *, /, %, ++, --
• 관계연산자 => 관계식 >, >=, <, <=, ==, !=
• 논리연산자 => 논리식 &&, ||, !
• 비트연산자 & ( 비트 논리곱 ), | ( 비트 논리합 ), ^ ( 배타적 논리합 ), >> ( 우측 쉬프트 ),
<< ( 좌측 쉬프트 )• 대입연산자 = 지정문 ( 대입문 : assignment statement) 에서 대입연산자를 사용 변수 = 식 ; 예 ) x = x + 5;
논리 연산자 (Logical Operators)
• 논리 연산을 수행한다 .
피연산자 1 피연산자2
AND(&&) OR(||) NOT(!)
false false false false true
false true false true true
true false false true false
true true true true false* NOT 연산자는 피연산자를 하나만 받는다 .
bool b1 = true;bool b2 = false;
bool and = b1 && b2;bool or = b1 || b2;bool not = ! b1;
관계연산자와 논리연산자
• 일반적으로 논리연산자는 관계연산자와 함께 사용한다 .
• 관계연산자의 우선순위가 높으므로 먼저 수행된다 .
int age = 20; // 나이bool male = true; // 성별
// 20 세 이상이면서 남성인지 여부를 알아봄bool ok = age >= 20 && male == true
연산자의 축약형• 연산자의 축약형을 사용해서 번거로운 코딩을 줄일 수 있다 .
축약형 같은 의미의 수식a += b; a = a + b;
a -= b; a = a – b;
a *= b; a = a * b;
a /= b; a = a / b;
a %= b; a = a % b;
a &= b; a = a & b;
a |= b; a = a | b;
a ^= b; a = a ^ b;
a <<= b; a = a << b;
a >>= b; a = a >> b;
연산중에 발생하는 형변환
• 두 피연산자의 타입이 다르다면 , 두 피연산자 중에서 보다 큰 타입 쪽으로 형변환이 발생한다 .
• int 보다 작은 타입들은 int 혹은 unsigned int 타입으로 변환된다 .
입출력 문 (input/output statement)
• 입력문 cin >> 변수 1 >> 변수 2 >> … >> 변수 n 화면으로부터 자료를 입력
• 출력문 cout << 변수 ( 식 혹은 문자열 ) << 변수 ( 식 혹은 문자열 ) … << 변수
( 식 혹은 문자열 ) 화면에 출력
2. 제어구조 (control struc-ture)
제어구조
• 판단 구조
– if– if /else
• 반복 구조
– for– While– do while
if 문
• 문법 if ( 조건 ) 문장• 조건 :
1. 관계식• 식 1 관계연산자 식 2 관계 연산자 : >, >= , <, <=, ==, !=
2. 논리식• 식 1 && 식 2, 식 1 and 식 2• 식 1 || 식 2, 식 1 or 식 2• ! 식 , not 식
• 블록– 여러 개의 문장들을 하나의 단위로 간주– { } 안에 둔다 .
조건
문장
if 문의 조건
• 조건의 예(1) 관계식 a != 0 a > b b*b > 4*a*c
(2) 논리식a > b and b > ca != 0 && b*b > 4*a*c !more // bool more;
if 문
• 예 :세 수를 입력하여 크기 순서대로 출력
x<yxy
시작
x, y,z
y<zyz
x<yxy
x,y,z 출력
끝
#include <iostream>using namespace std;int main(){ int x, y, z; cin >> x >> y >> z; int temp; if (x < y) { temp = x; x = y; y = temp; } if (y < z) { temp = y; y = z; z = temp;} if (x < y) { temp = x; x = y; y = temp;} cout << “정렬 결과 : “ << x << “ “ << y << “ “ << z << endl; return 0;}
if/else 문
• 문법 if ( 조건 ) 문장 1 else 문장 2
• 문제 : 세수를 입력하여 최대값을 출력하는 프로그램을 작성하시오
조건
문장 1문장 2
참거짓
if/else if … 문
• 문법 if ( 조건 1) 문장 1 else if ( 조건 2) 문장 2 else if ( 조건 3) …. else if ( 조건 n) 문장 n else 문장 0
조건 1 문장 1참
거짓
조건 2 문장 2참
조건 3 문장 3참
거짓
거짓
조건 n 문장 n참
거짓
문장 0
switch/case 를 사용한 조건 비교…int grade;level = score / 10;
switch ( level ){case 10:case 9:
cout << " 학점 : A \n";break;
case 8:cout << " 학점 : B \n";break;
case 7:cout << " 학점 : C \n";break;
case 6:cout << " 학점 : D \n";break;
default:cout << " 학점 : D \n";break;
}
• exp1 ? exp2 : exp3
int a = 3; int b = 5; int c = a > b ? a : b;
• Dangling( 매달린 ) else
if 문 안에 if 문이 중첩 (nested) 되어 있을 경우 , else 문이 if 문의 개수와 같지 않을 때 이 else 를 어느 if 와 대응 ?
=> 가장 가까운 if 와 대응시킴
예 : if (a > b) if (a > c) x = 10; else x = 20;
while 문
• 문법– while ( 조건 )
문장
조건
문장
참
거짓
i <= n
sum = sum + ii = i + 1;
참
거짓
sum =0;i = 1;
sum =0;i = 1;while (i <= n){ sum = sum + i; i++;}
• 문제 : 1 부터 n 까지의 합을 구하는 프로그램을 작성하시오 .
do/while 문
• 문법– do 문장 while ( 조건 )
조건
문장
참
거짓
for 문
• for( 문장 1; 조건 ; 문장 2) 문장 3;
– 문장 1 – 반복시작 전 초기화– 조건 – 반복 조건– 문장 3 - 반복 몸체– 문장 4 – 조건과 관련된 문장으
로 , 몸체 ( 문장 3) 를 수행한 후 , 마지막에 수행
• 횟수만큼 반복할 때 주로 사용• 예 for(i=1; i <=N; i++) 문장
조건
문장 3
참
거짓
문장 1
문장 2
for 문
• 예– N 을 입력받아 N! 을 출력하는
프로그램을 작성하라 .
i <= N
product= product * i
참
거짓
i = 1;
시작
N
product =1;
i++;product 를 출력
끝
#include <iostream>using namespace std;int main(){ int N; int i, product; cin >> N; product = 1; for(i = 1; i <= N; i++) product = product * i // product *= i; cout << N << “! = ” << product << endl; return 0;}
루프 안에서의 break
• 루프 (while, for) 나 switch 블록 안에서 break 를 사용하면 블록 밖으로 실행의 흐름이 이동된다 .
반복문 안에서의 continue
• continue 는 루프의 나머지 부분을 무시하고 조건을 반복문의 조건을 점검하는 곳으로 점프하여 루프의 다음을 실행하도록 하는 명령어
예 : void main() { int i; for (i=1;i<=50;i++) { if (i % 9 == 0) continue;
if (i % 3 == 0)printf("%d\n",i);
}}
연속된 입력값의 처리 – 표식을 이용
1) 입력의 마지막 값으로 입력으로 올 수 없는 값 ( 표식 : sen-tinel) 을 사용
– While loop 사용
• 성적들을 입력하여 평균을 구하는 프로그램을 작성하라 .
• 성적들을 입력하여 최고성적과 최저성적을 구하는 프로그램을 작성하라 .
#include <iostream>using namespace std;int main(){ int score; int n = 0; float sum = 0, avr; cin >> score; wihle (score != -1) // 표식값 : -1 { sum = sum + score; n++; cin >> score; } avr = sum/n; cout << “average = “ << avr << endl; return 0;}
연속된 입력값의 처리 – 자료개수를 이용
1) 입력자료의 개수를 처음에 입력– for loop 사용
• 성적들을 입력하여 평균을 구하는 프로그램을 작성하라 .
• 성적들을 입력하여 최고성적과 최저성적을 구하는 프로그램을 작성하라 .
#include <iostream>using namespace std;int main(){ int score; int n, i; float sum = 0, avr; cin >> n; for (i = 0; i <n; i++) { cin >> score; sum = sum + score; } avr = sum/n; cout << “average = “ << avr << endl; return 0;}
3. 배열 (Array)
배열• 의미
– 배열은 연속적인 항목들이 동일한 크기로 메모리에 저장되는 구조로 그 사용이 간편
– 배열은 동일한 자료 유형이 여러 개 필요한 경우에 이용할 수 있는 자료 구조
• 크기– 배열의 선언은 다음과 같은 구문을 이용
• 주요 요소는 배열 변수명 ( 이름 ), 자료형 , 그리고 배열의 크기
배열이름 score 로 정수 int 형 의 저 장 공 간 이 메 모 리 에 연 속 적 으 로 할당된다 .
배열 선언• Declaration of an array:
type arrayName[ arraySize ];
• Example• int c[12];
• arraySize must be an integer constant greater than zero.• type specify the types of data values to be stored in the array: can
be int, float, double, char, etc.
38
배열의 원소 (Elements of An Array)
• 배열의 특정한 원소 ( 혹은 위치 ) 를 참조하려면 다음을 명시하여야 함– Name of the array ( 배열 이름 ) – Index of the element ( 원소 인덱스 ) : 0 이상 값의 정수 혹은 정수 수식– 첫 번째 원소의 인덱스는 0
• Example C[0] += 2; C[a + b] = 3;
39
Example
40
• An array c has 12 elements ( c[0], c[1], … c[11] ); the value of c[0] is –45.
배열 초기화 – 초기화 리스트 이용
• Initializer list: items enclosed in braces ({}) and separated by com-mas.
• Examples– int n[ 5 ] = { 10, 20, 30, 40, 50 };
– int m[ 5 ] = { 10, 20, 30 };• The remaining elements are initialized to zero.
– int p[ ] = { 10, 20, 30, 40, 50 };• Because array size is omitted in the declaration, the compiler
determines the size of the array based on the size of the ini-tializer list.
41
배열 초기화 – 루프 이용
• Using a loop to initialize the array’s ele-ments– Declare array, specify number of elements– Use repetition statement to loop for each ele-
ment
• Example: int n[10]; for ( int i = 0; i < 10; i++) { n[ i ] = 0; }
42
배열 이용
• Usually use for loop to access each element of an array.
• C++ has no array boundary checking– Referring to an element outside the array bounds is an
execution-time logic error. It is not a syntax error.– You need to provide correct index.
43
배열 이용 – Example 1
• Example: 배열 원소들의 합 const int arraySize = 6; int a [ arraySize ] = { 87, 69, 45, 45, 43, 21 }; int total = 0; // need to initialize it!!! for ( int i = 0; i < arraySize; i++) { total += a[i]; } cout <<“Total of array elements is ”
<<total<<endl;
44
45
4. 구조체
46
구조체• 구조체 (structure)
– 여러 개의 자료형의 값들의 모임을 나타내는 자료형• 예 : 여러 사람의 학번 , 이름 , 학과를 저장하는 변수 선언
– 구조체를 사용하지 않은 경우int id1, id2, id3; …
학번char name1[10], name2[10], name3[10]; …
이름int dept1, dept2, dept3; …
학과코드– 구조체를 사용한 경우
struct student { … 구조체 정의 int id; … 학번 char name[10]; … 이름 int dept; … 학과코드
};struct student p1, p2, p3; … 구조체 변수
선언
47
구조체 정의
• 구조체의 사용– 구조체를 사용하기 위해서는 먼저 구조체의 자료 구조를 정의한다 .– 그 다음에 정의된 구조체의 자료형을 갖는 변수를 선언한다 .
• 구조체 정의struct student {
int id; … 학번 char name[10]; … 이름 int dept; … 학과코드
} ;
– student 구조체이름 , 태그 이름– id, name, dept 구조체 원소 , 필드 (field), 멤버
(member)
빠뜨리지 않도록 주의
48
구조체 변수 선언• 구조체 정의 후 변수 선언
struct student person;struct student p1, p2;
• 구조체 정의와 함께 변수 선언struct student {
int id; char name[10]; int dept;
} p1, p2;
49
구조체 정의와 변수 선언과의 관계 구조체 정의 구조체 변수 선언
id
dept
name
struct student
자료구조 정의
id
dept
name
id
dept
name
기억장소 할당
p1
p2
50
구조체 멤버 접근• 구조체 멤버 접근 : 구조체변수 . 멤버이름 ( 멤버연산자 .)
person.id person.name person.deptp1.id p1.name p1.dept
• 예person.id = 20030134; … 학번 초기화cin >> person.dept ; … 학과코드 입력
• 예 : 두 점 사이의 거리 계산– 2 차원 좌표를 구조체를 사용하여 나타냄#include <iostream>#include <cmath>using namespace std;
struct point { /* 2 차원 좌표 */float x;float y;
};
51
예제 ( 계속 )
main(){
struct point a, b; /* 두 점을 위한 변수 */float dx, dy, distance;
a.x = 10.0; a.y = 5.0; /* 첫 번째 점의 좌표 초기화 */cin>> b.x >> b.y; /* 두 번째 점의 좌표 입력 */
dx = a.x - b.x; /* 두 점의 x 좌표의 차이 */dy = a.y - b.y; /* 두 점의 y 좌표의 차이 */distance = sqrt(dx*dx + dy*dy); /* 두 점 사이의 거리 */cout <<"distance = “ << distance;
}
52
중첩된 구조체• 중첩된 구조체
– 구조체의 멤버로서 다른 구조체를 사용할 수 있음struct triangle { struct triangle
{ struct point a; 또는 struct
point a, b, c; struct point b; }; struct point c;
};
– 멤버의 접근struct triangle p;
p.a.x = 0;p.a.y = 10; … 구조체 멤버 접근 방법을… 반복하여 적용
53
예제 : 복소수 곱셈• 복소수의 곱셈
(a+bi) (c+di) = (ac-bd) + (ad+bc)i
#include <iostream>struct complex { /* 복소수 */
double real;double imag;
};
main(){
struct complex x = { 1.0, 2.0 }; /* 곱셈할 복소수 초기화 */struct complex y = { 2.0, -3.0 };struct complex m; /* 곱셈 결과 */
m.real = x.real * y.real - x.imag * y.imag;m.imag = x.real * y.imag + x.imag * y.real;cout << " 복소수 곱셈결과 = “ <<m.real < “ + ”<<m.imag << “i”;
}
54
구조체의 치환과 비교
• 구조체의 치환은 허용됨– 구조체의 모든 멤버들이 복사됨
• 구조체의 비교는 허용되지 않음– 개별적으로 멤버 비교해야 함
struct point p1 = {4.0, 10.0};struct point p2;
p2 = p1; /* 구조체 치환 */cout << "p2: x = “ << p2.x << “p2:y = “ << p2.y);
if (p1.x == p2.x && p1.y == p2.y) /* 구조체 비교 : 멤버 별로 */
cout <<" 두 점 p1 과 p2 는 같다 .\n";
55
구조체 배열
• 구조체의 배열– 여러 개의 같은 구조체 자료형의 모임을 나타내는 자료형
• 예 : 10 명의 학생의 자료를 입력 받아서 역순으로 출력struct student {
int id; string name; int dept;};
main(){
int i;student s[10]; /* s 는 구조체의 배열 */
for (i=0; i<10; i++) cin >> s[i].id >> s[i].name >> s[i].dept;
for (i=0; i<10; i++) cout << s[i].id << “ “ << s[i].name << “ “ << s[i].dept << endl;
}
5. 함수 (function)
프로그래밍에서의 함수
• 왜 함수를 사용하는가 ?
– 프로그래밍 설계 전략
– Divide-and-Conquer• 어떤 문제를 해결하기 위해 여러 개의 작은 문제로 쪼개는 것 .• 사람이 일을 처리하는 방법도 비슷
– 프로그램의 작성이 용이– 반복적인 일을 수행하는 경우 원시파일의 크기를 줄일 수 있음 .
함수 유형
• 라이브러리 함수– 라이브러리 함수는 이미 정의되어 있고 컴파일되어 있음– 표준 라이브러리 헤더 파일에서 원형을 제공– 함수의 원형 (prototype) 에 맞게 호출
• 사용자 정의 함수– 사용자가 직접 함수 작성– main 도 사용자 정의 함수
함수 정의
프로그램은 하나 이상의 함수로 구성됨 함수정의−함수가 수행할 일을 기술한 C 코드 함수정의의 일반적인 형식 {
declarationsstatements
}
반환형 (return type)
• 함수가 반환하는 값의 자료형• 이것이 void 이면 반환하는 값이 없다는 것을 나타냄
인자 (parameter) 리스트• 이 함수가 가지는 인자의 목록• 이 함수를 호출할 때에는 이 리스트에 맞게 호출해야함• 이것이 void 이면 인자를 갖지 않음을 나타냄
함수 정의 - 예
예 :double abs(double x){ if (x >= 0) return x; else return –x;}
예 :int max (int x, int y){ if (x >y) return x; else return y;}
return 문장
return 문 (1) 형식 return 식 ; 의미 - 함수 결과로서 식의 값을 반환하고 함수를 빠져나간다 .
(2) 형식 return; 함수의 반환형이 void 의미 - 이 문장을 수행하면 함수를 빠져나간다 . 함수의 수행 중 마지막을 만나면 함수를 빠져나간다 . – return 문장의
수행과 동일한 효과
함수의 인자 (parameter)
인자 (parameter)
함수에 자료를 전달하는 방법 실제인자 (actual parameter) - 함수 사용에 있는 인자 형식인자 (formal parameter) - 함수 정의에 있는 인자
함수 작성 예
• Task: write ExchangeValue function that exchange the value of two parameters, both integers
int x=10, y=20; Exchange(x,y); cout <<“x=“<<x<<endl; cout << “y=“<<y<<endl;
63
Should print out: x=20 y=10
C/C++ function
void ExchangeValue(int a, int b){
int tmp;tmp=a;a=b;b=tmp;
}
void main( ){ int myInteger1=4; int myInteger2=5;
ExchangeValue(myInteger1,myInteger2); cout<<“integer1=
“<<myInteger1<<endl<<“integer2=“<<myInteger2<<endl;}
64
a,b: formal parameters
actual parameters
올바르게 동작하느냐 ?
Call by value: A copy of the value of myInterger1 and myInterger2 are passed to ExchangeValue.
C++ Tips
65
CALLINGBLOCK
FUNCTION CALLED
Pass-by-value sends a copy of the value of the actual parameter
SO, the actual parameter cannot be changed by the function
C++ Tips
66
CALLINGBLOCK FUNCTION
CALLED
Pass-by-reference sends the location (memory address) of the actual parameter
the actual parameter can be changed by the function
Call-by-reference
• Good for performance reason: eliminate copying overhead
• Called the same way as call-by-valueint squareByValue (int x);int squareByReference (int & x);int x,z;…squareByValue(x);squareByReference(z);
• Bad for security: called function can corrupt caller’s data– Solution: use const quantifier
67
C/C++ function: call by reference
void ExchangeValue(int & a, int & b){
int tmp;tmp=a;a=b;b=tmp;
}
int main(int argc, char ** argv){ int value1=4; int value2=5; int result=ExchangeValue(value1,vaule2); cout<<“value=
“<<value1<<endl<<“value2=“<<value2<<endl;}
68
a,b: formal parameters
actual parameters
제대로 동작함 !
Passing Arrays as Parameters
• In C/C++, arrays are always passed by reference– & is not used in the formal parameter type.– Whenever an array is passed as a parameter, its base ad-
dress is sent to called function
• Example: // prototype float SumValues (float values [], int numOfValues );
69
const array parameter
If the function is not supposed to change the array:you can protect the array from unintentional changes, use const in formal parameter list and function prototype.
FOR EXAMPLE . . . // prototype
float SumValues( const float values[ ], int numOfValues );
70
If there is statement inside SumValues() that changes values of values array, compiler will report error.
// Pre: values[0] through values[numOfValues-1] // have been assigned
// Returns the sum of values[0] through// values[numOfValues-1]
float SumValues (const float values[ ], int numOfValues )
{ float sum = 0;
for ( int index = 0; index < numOfValues; index++ ) {
sum += values [ index ] ; }
return sum;}
71
6. 포인터 (pointer)
Pointer Variable• A variable whose value is the address of a
location in memory• i.e., a variable that points to some address
in memory…• type * pointer_variable_name;
73
int* intPointer
Assign Value to Pointer
74
int alpha;int* intPointer;
intPointer = α
If alpha is at address 33, memory looks like this
alpha
Pointer Types
int x; x = 12;
int* ptr; ptr = &x;
Because ptr holds the address of x, we say that ptr “points to” x
75
2000
12
x
3000
2000
ptr
Pointer: Dereference Operator (*) • An operator that, when applied to a
pointer variable, denotes the variable to which the pointer points
76
int x; x = 12;
int* ptr; ptr = &x;
std::cout << *ptr;
*ptr is the value in the place to which ptr points
2000
12
x
3000
2000
ptr
Pointer: Dereference Operator (*)
int x; x = 12;
int* ptr; ptr = &x;
*ptr = 5;
// changes the value
// at adddress ptr to 5
77
2000
12 5
x
3000
2000
ptr
Pointer Types char ch; ch = ‘A’;
char* q; q = &ch;
*q = ‘Z’; char* p; p = q;
// the right side has value 4000
// now p and q both point to ch
78
4000
A Z
ch
5000 6000
4000 4000
q p
Pointer Types
• All pointer variables should be ini-tialized to be NULL
– A pointer that points to nothing; available in <cstdlib>
– NULL is defined to be 0;– But NULL is not memory address 0
int * intPtr = NULL;Float * money = NULL;
79
intPtr money
Review: lifetime of variables or ob-jects
• Global variables/objects: start from before the program starts until main() ends
int num; main(){
…. }
• Local variables/objects: declared within the body of a function or a block – Created upon entering the function/block, destroyed
upon exiting the function/block• Dynamical variables/objects: created using new(), mal-
loc() calls– Remains alive until delete() is called to free the
memory– Destroyed upon the program exits
80
Dynamic allocation (new operator)
• Allocation of memory space for a variable at run time (as opposed to static allocation at compile time)
81
int * intPointer;intPointer = new int;
Deallocate allocated mem-ory
• Dynamically allocated memory needs to be deallocated when it’s no more used– Otherwise, memory leak will degrade performance
• delete operator returns memory to sys-tem delete p;– Value of p is unchanged, i.e. pointing to a deallocated
memory– Accessing a deallocated memory (*p) can be dangerous – Always set to NULL after deallocation
delete p; // free up memory pointed to by pp = NULL; // safeguard, extremely important
82
Pointers: examples
Figure 4-3 (a) Declaring pointer variables; (b) pointing to statically allocated memory; (c) assigning a value;
(d) allocating memory dynamically; (e) assigning a value
83
Pointers: example (cont’d)
84
This memory space cannot be deallocated, as we don’t have a pointer …
Dynamically Allocated Ar-rays
• Use new operator to allocate an array dynamically int arraySize;
//ask user to enter arraySize…//
double *anArray = new double[arraySize];
– arraySize has a value determined at run time
• Dynamically allocated array can be increased double *oldArray = anArray; anArray = new double[2*arraySize]; // copy from oldArray to anArray delete [] oldArray; // deallocate oldArray
85
7. Data Design
Let’s focus on: Data
• Data: the representation of information in a manner suitable for communication or analysis by humans or machines
• Data are the nouns of the programming world: – The objects that are manipulated– The information that is processed
• Different view about data– Application view: what real life object can be mod-
eled using the data ?– Logic view: how to use the data ? Operations ?– Implementation view: how to implement the data ?
87
88
C++ Built-In Data Types
Composite
array struct union class
Address
pointer reference
Simple
Integral Floating
char short int long enum
float double long double
Using C/C++ Data Type
• As a C/C++ programmer, we know – Based on the application, we model them
as different “variables”• Age: integer• Gender: enumeration• Name: array of char, or string
– Also we know what kind of operations each data type supports
• We do not worry about how an integer is implemented– Unless in computer organization class …
89
C++ programmer are user of int
90
Value range: INT_MIN . . INT_MAX
Operations: + prefix - prefix + infix - infix * infix / infix % infixRelational Operators infix
TYPE int
(inside)
Representation of
int
as 16 bits two’s complement
+
Implementation of Operations
Different Views of Data
• Application (or user) level modeling real-life data in a specific context– When to use a certain data type ?
• Logical (or ADT) level abstract view of the domain and operations – What– How to use the data type ?
• Implementation level specific representa-tion of the structure to hold the data items, and the coding for operations – How to implement the data type ?
91
Different Views of Data: Library Example
• Application (or user) level Library of Con-gress, or Baltimore County Public Library– A library system can be implemented for Li-
brary of Congress…
• Logical (or ADT) level domain is a collection of books; operations include: check book out, check book in, pay fine, reserve a book– A library’s necessary functions to outside world
• Implementation level representation of the structure to hold the “books” and the coding for operations– How a specific library is implemented (how are books
organized…)?
92
• A two-dimensional array – A structured composite data type made up of a fi-
nite, fixed size collection of homogeneous elements ordered in two dimensions and for which direct ac-cess is provided:
• dataTable[row][col]
93
logical levelint dataTable[10][6];
Logic view of 2D array:all a C++ program needs to know
Many recurrent data types
• List• Queue: First In First Out
– Operating System: process queues, printing job queue
• Stack: Last in First out– Calling stack– Compiler: to parse expressions
• Graph:– Model computer network– ….
94
Provide a high-level data type with these logic property
Data Abstraction: the idea• Data Abstraction: the separation of a data type’s
logical properties from its implementation– User of the data type only needs to understand its log-
ical property, no need to worry about its implementa-tion
95
LOGICAL PROPERTIES IMPLEMENTATION
What are the possible values? How can this be done in C++?
What operations will be needed?
Abstract Data Type: A logic view
• Abstract Data Type is a specification of– a set of data – the set of operations that can be performed on the
data • Constructors: to creates new instances of an ADT;
usually a language feature• Transformers (mutators): operations that change
the state of one or more data values in an ADT• Observers: operations that allow us to observe the
state of the ADT• Iterators: operations that allow us to access each
member of a data structure sequentially
• Abstract Data Type is implementation independent
96
OOP & ADT
• Object-oriented language provide mechanism for specifying ADT and implementing ADT
• Class – An unstructured type that encapsulates a
fixed number of data components (data members) with the functions (member func-tions) that manipulate them
– predefined operations on an instance of a class are whole assignment and component access
• Client– Software that uses (declares and manipu-
lates) objects (instances) of a particular class to solve some problem
97
Object-Oriented Programming: Basics
•Class – an unstructured type that encapsulates a fixed number of data components (data members) with the functions (called member functions) that manipulate them
•Object –An instance of a class
•Method–A public member function of a class
•Instance variable (Data Member)–A private data member of a class
98
Higher-Level Abstraction
• Class specification– A specification of the class members (data
and functions) with their types and/or pa-rameters
• Class implementation– The code that implements the class func-
tions
99
Why would you want toput them in separate files?
Classes vs. Structs
• Without using public and private, member functions and data are– private by default in classes – public by default in structs.
• Usually, there is no member func-tions defined in structs– struct is passive data– class is active data
100
class DateType Specification
// SPECIFICATION FILE ( datetype.h )
class DateType // declares a class data type{
public : // 4 public member functions
DateType (int newMonth,int newDay,int newYear);//constructorint getYear( ) const ; // returns yearint getMonth( ) const ; // returns monthint getDay( ) const ; // returns day
private : // 3 private data members
int year ; int month ; int day ;
} ;
101101
Use of C++ data type class• Variables of a class type are called objects (or in-
stances) of that particular class.
• Software that declares and uses objects of the class is called a client.
• Client code uses public member functions (called methods in OOP) to handle its class objects.
• Sending a message means calling a public member function.
102
Client Code Using DateType#include “datetype.h” //includes specification of the class#include <iostream>using namespace std;int main ( ){ // declares two objects of DateType
DateType startDate ( 6, 30, 1998 ) ; DateType endDate ( 10, 31, 2002 ) ;
bool retired = false ;
cout << startDate.getMonth( )<< “/” << startDate.getDay( ) << “/” << startDate.getYear( ) << endl;
while ( ! retired ) { finishSomeTask( ) ; . . . } return 0; }
103103
How to dynamically create a DateType object ?
2 separate files for class type
// SPECIFICATION FILE ( datetype .h ) // Specifies the data and function members. class DateType { public: . . .
private: . . . } ;
// IMPLEMENTATION FILE ( datetype.cpp )
// Implements the DateType member functions. . . .
104
Implementation of member func-tions
// IMPLEMENTATION FILE (datetype.cpp)#include “datetype.h” // also must appear in client code
DateType :: DateType ( int newMonth, int newDay, int newYear )// Post: year is set to newYear.// month is set to newMonth.// day is set to newDay.{ year = newYear ; month = newMonth ; day = newDay ;}
105105
:: Scope resolution operator
C++ Classes: Construc-tors
• Invoked/called (automatically) when an object of the class is declared/created
• A class can have several constructors– A default constructor has no arguments– different constructors with different parameter list (sig-
nature)• Eg. DateType can be extended to have the following con-
structor :• DateType (int secondsSinceEpoch);
– The compiler will generate a default constructor if you do not define any constructors
106
int DateType :: getMonth ( ) const// Accessor function for data member month{ return month ;}
int DateType :: getYear ( ) const// Accessor function for data member year{ return year ;}
int DateType :: getDay ( ) const// Accessor function for data member day{ return day ;}
107107
C++ Classes: Destruc-tors*
• Called (automatically) when an object’s lifetime ends– To free up resources taken by the object,
esp. memory• Each class has one destructor
– If you don’t need to free up resources, you can omit define destructor and the compiler will generate a default destructor
108
C++ Namespaces*
• A mechanism for logically grouping declarations and definitions into a common declarative regionnamespace myNamespace
{ // Definitions
// Declarations . . .} //end myNamespace
• The contents of the namespace can be accessed by code inside or outside the namespace– Use the scope resolution operator (::) to access
elements from outside the namespace– Alternatively, the using declaration allows the
names of the elements to be used directly
109
C++ Namespace: simple example*
• Creating a namespacenamespace smallNamespace{ int count = 0; void abc();} // end smallNamespace
• Using a namespacesmallNamesapce::count=0;using namespace smallNamespace;count +=1;abc();
110
C++ std namespace*
• Items declared in the C++ Standard Li-brary are declared in the std names-pace
• You include files for several functions declared in the std namespace – To include input and output functions from
the C++ library, write #include <iostream>
using namespace std;
111
Encapsulation
• Just as a capsule protects its contents, the class construct protects its data members
112
// SPECIFICATION FILE ( datetype.h )
class DateType{Public :
DateType (int newMonth,int newDay,int newYear);//constructor
int getYear( ) const ; int getMonth( ) const ; int getDay( ) const ;
private :int year ; int month ; int day ;
} ;
Object-Oriented Pro-gramming
•Three ingredients in any object-oriented language
– encapsulation– inheritance– polymorphism
113
Inheritance• Inheritance: A mechanism used with a hierarchy of classes in which each descen-dant class inherits the proper-ties (data and operations) of its ancestor class
•Base class– The class being inherited
from
•Derived class– the class that inherits
114Inheritance is an "is-a" …
Overriding & Polymorphism
• Polymorphism: the ability to determine which of sev-eral operations with the same name (within the class hi-erarchy) is appropriate, either at compiling time (static binding) or run time (dynamic binding)
• Overriding• Function with virtual keyword in base class.• Derived classes override function as appropriate. • An overridden function in a derived class has the
same signature and return type (i.e. prototype) as the function it overrides in its base class.
115
Example: Overriding
116
Person
Employee
Manager
Each class has a method Print
Person.Print just prints the name
Employee.Print prints the name and job title
Manager.Print prints name, job title, and department
Print is overriden.
* Static binding is when the compiler can tell which Print to use
* dynamic binding is when the determination cannot be made until run time => use the virtual keyword
Object-Oriented Program-ming
•Inheritance and polymorphism work together to al-low programmer to build useful hierarchies of classes that can be put into a library to be reused in different applications•Examples:
– Employee class can reuse features implemented at Person class– Only override functions when needed, like print()– A program working for Person class still work for Employee object (through polymorphism)
• Print out all persons,…117
Miscellaneous: I/O in C++• Header files iostream and fstream declare the
istream, ostream,and ifstream, ofstream I/O classes.
• Both cin and cout are class objects• These statements declare myInfile as an instance
of class ifstream and invoke member function open.ifstream myInfile ;myInfile.open ( “A:\\mydata.dat” ) ;
118