기본적인 자료형 (DataType)변수(variable): 자료를 저장하는 기억장소- 모든 변수는 자료형이 지정되어 있어야 하고, 한번 지정된 자료형은 변할 수 없다.- 변수를 사용하기 전에 변수를 미리 정의해야 한다.자료형_이름 변수리스트;자료형_이름: 정수형: int, short int, long, unsigned int, …실수형: float, double, …문자형: char부울형: bool, …연산자 sizeof - 자료형의 크기예 sizeof(int)
4.
변수의 이름에대한규칙중복된 이름의변수를 사용할 수 없다.변수 이름에는 알파벳, 숫자, 언더스코어(_)만 포함할 수 있다.단, 숫자는 변수 이름의 첫 번째 글자로 사용할 수 없다.변수 이름의 길이에는 제한이 없다.변수 이름에 포함하는 알파벳은 대소문자를 구분한다.키워드는 변수의 이름으로 사용할 수 없다.
5.
변수의 이름을 붙일경우변수의 용도에 맞는 이름예: StudentsNumber변수내의 단어와 단어는 구분예: StudentsNumber, student_number필요 없이 긴 이름은 피함
정수 타입 (Integers)정수타입별로 보관할 수 있는 값의 범위10 진수, 8 진수, 16 진수의 표현* 32비트 윈도우즈 시스템을 기준으로 한 값int decimal = 41; // 10 진수int octal = 041; // 8 진수int hexadecimal = 0x41; // 16 진수
문자 타입 (Characters)문자타입별로 보관할 수 있는 값의 범위문자 타입도 결국은 숫자를 보관한다.* 32비트 윈도우즈 시스템을 기준으로 한 값
10.
부울 타입 (Boolean)부울타입은 true 혹은 false의 값을 갖는다.bool b1;bool b2;b1 = true;b2 = false;cout << “b1 = “ << b1 << “\n”;cout << “b2 = “ << b2 << “\n”;
11.
형 변환내부적 형변환암시적 형변환은 변수에 대한 처리 과정에서 자동적으로 발생하는 형변환이다. 이 때 값이 변할 수 있다. 예: 실수 타입에서 정수 타입으로 형변환 발생 시 소수점 이하 부분이 잘린다. (반올림 아님)강제 형 변환 1) (type) expression 예 float f = 66.89; int i = (int)f; // i는 66 이 된다. 2) static_cast <자료형 이름>(수식)예: int n = static_cast<int>(y+0.5);
12.
상수Define - 매크로예)#define pi 3.14const 자료형이름 상수이름 = 초기값; 예) const double pi = 3.14;
논리 연산자 (LogicalOperators)논리 연산을 수행한다.bool b1 = true;bool b2 = false;bool and = b1 && b2;bool or = b1 || b2;bool not = ! b1;* NOT 연산자는 피연산자를 하나만 받는다.
15.
관계연산자와 논리연산자일반적으로 논리연산자는관계연산자와 함께 사용한다.관계연산자의 우선순위가 높으므로 먼저 수행된다.int age = 20; // 나이bool male = true; // 성별// 20세 이상이면서 남성인지 여부를 알아봄bool ok = age >= 20 && male == true
if 문문법 if(조건)문장조건:1. 관계식식1 관계연산자 식2관계 연산자:>, >= , <, <=, ==, !=2. 논리식식1 && 식2, 식1 and 식2식1 || 식2, 식1 or 식2 ! 식, not 식블록여러 개의 문장들을 하나의 단위로 간주{ } 안에 둔다.조건문장
22.
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;
23.
시작x, y,zx<yxyy<zyzx<yxyx,y,z 출력끝if문예:세 수를 입력하여 크기 순서대로 출력#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;}
exp1 ? exp2: exp3int 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;
28.
참조건문장거짓sum =0;i =1;참i <= nsum = sum + ii = i + 1;거짓while 문문법while (조건)문장문제: 1부터 n까지의 합을 구하는 프로그램을 작성하시오.sum =0;i = 1;while (i <= n){ sum = sum + i; i++;}
for 문for(문장1; 조건;문장2)문장3;문장1 –반복시작 전 초기화조건 –반복 조건문장3 - 반복 몸체문장4 –조건과 관련된 문장으로, 몸체(문장3)를 수행한 후, 마지막에 수행 횟수만큼 반복할 때 주로 사용예for(i=1; i <=N; i++)문장문장1참조건문장3거짓문장2
31.
for 문시작N예N을 입력받아N!을 출력하는 프로그램을 작성하라.product =1;i = 1;#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;}참i <= Nproduct= product * i거짓i++;product를 출력끝
반복문 안에서의 continuecontinue는루프의 나머지 부분을 무시하고 조건을 반복문의 조건을 점검하는 곳으로 점프하여 루프의 다음을 실행하도록 하는 명령어예: void main() { int i; for (i=1;i<=50;i++) { if (i % 9 == 0) continue; if (i % 3 == 0) printf("%d\n",i); }}
34.
연속된 입력값의 처리–표식을 이용1) 입력의 마지막 값으로 입력으로 올 수 없는 값(표식: sentinel)을 사용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;}
35.
연속된 입력값의 처리–자료개수를이용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;}
배열의미배열은 연속적인 항목들이동일한 크기로 메모리에 저장되는 구조로 그 사용이 간편배열은 동일한 자료 유형이 여러 개 필요한 경우에 이용할 수 있는 자료 구조크기배열의 선언은 다음과 같은 구문을 이용주요 요소는 배열 변수명(이름), 자료형, 그리고 배열의 크기배열이름 score 로 정수 int 형의 저장 공간이 메모리에 연속적으로 할당된다.
38.
배열 선언Declaration ofan array:type arrayName[ arraySize ];Exampleint 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
39.
배열의원소(Elements of AnArray)배열의특정한 원소(혹은 위치)를 참조하려면 다음을 명시하여야 함Name of the array (배열 이름)Index of the element (원소 인덱스) : 0 이상 값의 정수 혹은 정수 수식첫 번째 원소의 인덱스는 0ExampleC[0] += 2;C[a + b] = 3;39
40.
Example40An array chas 12 elements ( c[0], c[1], … c[11] ); the value of c[0] is –45.
41.
배열 초기화 –초기화 리스트 이용Initializer list: items enclosed in braces ({}) and separated by commas.Examplesint 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 initializer list.41
42.
배열 초기화 –루프 이용Using a loop to initialize the array’s elementsDeclare array, specify number of elementsUse repetition statement to loop for each elementExample:int n[10]; for ( int i = 0; i < 10; i++) { n[ i ] = 0; }42
43.
배열 이용Usually usefor loop to access each element of an array. C++ has no array boundary checkingReferring 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
44.
배열 이용 –Example 1Example: 배열 원소들의 합 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
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.
47구조체 정의구조체의 사용구조체를사용하기 위해서는 먼저 구조체의 자료 구조를 정의한다.그 다음에 정의된 구조체의 자료형을 갖는 변수를 선언한다.구조체 정의struct student { int id; … 학번 char name[10]; … 이름int dept; … 학과코드} ;student 구조체이름, 태그 이름id, name, dept 구조체 원소, 필드(field), 멤버(member)빠뜨리지 않도록 주의
48.
48구조체 변수 선언구조체정의 후 변수 선언struct student person; struct student p1, p2;구조체 정의와 함께 변수 선언struct student { int id; char name[10]; int dept; } p1, p2;
49.
49구조체 정의와 변수선언과의 관계구조체 정의 구조체 변수 선언idp1struct studentnameiddeptnamep2deptidname자료구조 정의dept기억장소 할당
50.
50구조체 멤버 접근구조체멤버 접근: 구조체변수.멤버이름 (멤버연산자 .) person.id person.name person.dept p1.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.
51예제 (계속) main(){structpoint 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.
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; … 구조체 멤버 접근 방법을… 반복하여 적용
함수 정의 -예예:int max (int x, int y){ if (x >y) return x; else return y;}예:double abs(double x){ if (x >= 0) return x; else return –x;}
65.
return 문장 return문(1) 형식 return 식;의미 - 함수 결과로서 식의 값을 반환하고 함수를 빠져나간다. (2) 형식 return;함수의 반환형이 void의미 - 이 문장을 수행하면 함수를 빠져나간다.함수의 수행 중 마지막을 만나면 함수를 빠져나간다. – return 문장의 수행과 동일한 효과 함수의 인자(parameter)인자(parameter)
함수작성 예Task: writeExchangeValue 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; 63Should print out: x=20 y=10
69.
C/C++ functionvoid ExchangeValue(inta, int b){inttmp;tmp=a;a=b;b=tmp;}void main( ){int myInteger1=4;int myInteger2=5;ExchangeValue(myInteger1,myInteger2);cout<<“integer1= “<<myInteger1<<endl<<“integer2=“<<myInteger2<<endl;}64a,b: formal parameters올바르게 동작하느냐? Call by value: A copy of the value of myInterger1 and myInterger2 are passed to ExchangeValue.actual parameters
70.
C++ Tips65CALLINGBLOCKFUNCTION CALLEDPass-by-value sends a copyof the value of the actual parameterSO, the actual parameter cannot be changed by the function
71.
C++ Tips66CALLINGBLOCKFUNCTION CALLEDPass-by-reference sends the location(memory address) of the actual parameterthe actual parameter can be changed by the function
72.
Call-by-referenceGood for performancereason: eliminate copying overheadCalled 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 dataSolution: use const quantifier67
Passing Arrays asParametersIn 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 address is sent to called functionExample:// prototype float SumValues (float values [], int numOfValues );69
75.
constarray parameter Ifthe 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 );70If there is statement inside SumValues() that changes values of values array, compiler will report error.
76.
// Pre: values[0] through values[numOfValues-1] // have been assigned// Returns the sum of values[0] through// values[numOfValues-1]float SumValues(constfloat values[ ], int numOfValues ){ float sum = 0; for ( int index = 0; index < numOfValues; index++ ) { sum += values [ index ] ; } return sum;}71
Pointer VariableA variablewhose value is the address of a location in memoryi.e., a variable that points to some address in memory…type * pointer_variable_name;73int* intPointer
79.
Assign Value toPointer74int alpha;int* intPointer;intPointer = αIf alpha is at address 33, memory looks like thisalpha
80.
Pointer Types75 2000 12 x3000 2000 ptrint x; x = 12; int* ptr; ptr = &x;Because ptr holds the address of x, we say that ptr “points to” x
81.
Pointer: Dereference Operator(*) An operator that, when applied to a pointer variable, denotes the variable to which the pointer points76 2000 12 x3000 2000 ptrint x; x = 12; int* ptr; ptr = &x; std::cout << *ptr;*ptr is the value in the place to which ptr points
82.
77Pointer: Dereference Operator(*) 2000 12 5 x3000 2000 ptrint x; x = 12; int* ptr; ptr = &x; *ptr = 5;// changes the value // at adddress ptr to 5
83.
Pointer Types78char 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 4000 A Z ch5000 6000 4000 4000 q p
84.
79intPtrmoneyPointer TypesAll pointervariables should be initialized to be NULLA pointer that points to nothing; available in <cstdlib>NULL is defined to be 0;But NULL is not memory address 0int * intPtr = NULL;Float * money = NULL;
85.
Review: lifetime ofvariables or objectsGlobal variables/objects: start from before the program starts until main() endsint 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/blockDynamical variables/objects: created using new(), malloc() callsRemains alive until delete() is called to free the memoryDestroyed upon the program exits80
86.
Dynamic allocation (newoperator)Allocation of memory space for a variable at run time (as opposed to static allocation at compile time)81int * intPointer;intPointer = new int;
87.
Deallocate allocated memoryDynamicallyallocated memory needs to be deallocated when it’s no more usedOtherwise, memory leak will degrade performancedelete operator returns memory to system delete p;Value of p is unchanged, i.e. pointing to a deallocated memoryAccessing a deallocated memory (*p) can be dangerous Always set to NULL after deallocation delete p; // free up memory pointed to by p p = NULL; // safeguard, extremely important82
88.
Pointers: examplesFigure 4-3(a)Declaring pointer variables; (b) pointing to statically allocated memory; (c) assigning a value;(d) allocating memory dynamically; (e) assigning a value83
Dynamically Allocated ArraysUsenew operator to allocate an array dynamicallyint arraySize; //ask user to enter arraySize… //double *anArray = new double[arraySize];arraySize has a value determined at run timeDynamically allocated array can be increaseddouble *oldArray = anArray; anArray = newdouble[2*arraySize]; // copy from oldArray to anArray delete [] oldArray; // deallocate oldArray85
Let’s focus on:DataData: the representation of information in a manner suitable for communication or analysis by humans or machinesData are the nouns of the programming world: The objects that are manipulatedThe information that is processedDifferent view about dataApplication view: what real life object can be modeled using the data ?Logic view: how to use the data ? Operations ?Implementation view: how to implement the data ? 87
93.
88 Addresspointer referenceC++ Built-In Data TypesSimpleComposite IntegralFloatingarray struct union classchar short int long enumfloat double long double
94.
Using C/C++ DataTypeAs a C/C++ programmer, we know Based on the application, we model them as different “variables”Age: integerGender: enumerationName: array of char, or stringAlso we know what kind of operations each data type supportsWe do not worry about how an integer is implementedUnless in computer organization class …89
95.
C++ programmer areuser of int90TYPE intRepresentation of int as 16 bits two’s complement +Implementation of OperationsValue range: INT_MIN . . INT_MAX Operations: + prefix - prefix + infix - infix* infix / infix% infixRelational Operators infix(inside)
96.
Different Views ofDataApplication (or user) levelmodeling real-life data in a specific contextWhen to use a certain data type ?Logical (or ADT) levelabstract view of the domain and operationsWhatHow to use the data type ?Implementation levelspecific representation of the structure to hold the data items, and the coding for operationsHow to implement the data type ? 91
97.
Different Views ofData: Library ExampleApplication (or user) levelLibrary of Congress, or Baltimore County Public LibraryA library system can be implemented for Library of Congress…Logical (or ADT) leveldomain is a collection of books; operations include: check book out, check book in, pay fine, reserve a bookA library’s necessary functions to outside worldImplementation levelrepresentation of the structure to hold the “books” and the coding for operationsHow a specific library is implemented (how are books organized…)? 92
98.
A two-dimensional arrayAstructured composite data type made up of a finite, fixed size collection of homogeneous elementsordered in two dimensions and for which direct access is provided:dataTable[row][col]93Logic view of 2D array:all a C++ program needs to knowlogical levelint dataTable[10][6];
99.
Many recurrent datatypesListQueue: First In First OutOperating System: process queues, printing job queueStack: Last in First outCalling stackCompiler: to parse expressionsGraph:Model computer network….94Provide a high-level data type with these logic property
100.
Data Abstraction: theideaData Abstraction: the separation of a data type’s logical properties from its implementationUser of the data type only needs to understand its logical property, no need to worry about its implementation95LOGICAL PROPERTIES IMPLEMENTATIONWhat are the possible values? How can this be done in C++?What operations will be needed?
101.
Abstract Data Type:A logic viewAbstract Data Type is a specification ofa 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 featureTransformers (mutators): operations that change the state of one or more data values in an ADTObservers: operations that allow us to observe the state of the ADTIterators: operations that allow us to access each member of a data structure sequentiallyAbstract Data Type is implementation independent96
102.
OOP & ADTObject-orientedlanguage provide mechanism for specifying ADT and implementing ADTClassAn unstructured type that encapsulates a fixed number of data components (data members) with the functions (member functions) that manipulate thempredefined operations on an instance of a class are whole assignment and component accessClientSoftware that uses (declares and manipulates) objects (instances) of a particular class to solve some problem97
103.
Object-Oriented Programming: BasicsClassan unstructured type that encapsulates a fixed number of data components (data members) with the functions (called member functions) that manipulate themObjectAn instance of a classMethodA public member function of a classInstance variable (Data Member)A private data member of a class98
104.
Higher-Level AbstractionClass specificationAspecification of the class members (data and functions) with their types and/or parametersClass implementationThe code that implements the class functions99Why would you want toput them in separate files?
105.
Classes vs. StructsWithoutusing public and private, member functions and data areprivate by default in classes public by default in structs.Usually, there is no member functions defined in structsstruct is passive dataclass is active data100
106.
classDateType Specification// SPECIFICATION FILE ( datetype.h )class DateType// declares a class data type{public : // 4 public member functions DateType (int newMonth,int newDay,int newYear);//constructor int getYear( ) const ; // returns year int getMonth( ) const ; // returns month int getDay( ) const ; // returns dayprivate : // 3 private data members int year ; int month ; int day ;} ;101101
107.
Use of C++data type classVariables of a class type are called objects (or instances) 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
108.
Client Code UsingDateType#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; }103How to dynamically create a DateType object ?103
109.
2 separate filesfor 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
110.
Implementation of memberfunctions// IMPLEMENTATION FILE (datetype.cpp)#include “datetype.h” // also must appear in client codeDateType :: 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 ;}105:: Scope resolution operator105
111.
C++ Classes: ConstructorsInvoked/called(automatically) when an object of the class is declared/createdA class can have several constructorsA default constructor has no argumentsdifferent constructors with different parameter list (signature)Eg. DateType can be extended to have the following constructor :DateType (int secondsSinceEpoch);The compiler will generate a default constructor if you do not define any constructors106
112.
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
113.
C++ Classes: Destructors*Called(automatically) when an object’s lifetime endsTo free up resources taken by the object, esp. memoryEach class has one destructorIf you don’t need to free up resources, you can omit define destructor and the compiler will generate a default destructor108
114.
C++ Namespaces*A mechanismfor logically grouping declarations and definitions into a common declarative regionnamespace myNamespace { // Definitions // Declarations . . .} //end myNamespaceThe contents of the namespace can be accessed by code inside or outside the namespaceUse the scope resolution operator (::) to access elements from outside the namespaceAlternatively, the using declaration allows the names of the elements to be used directly109
115.
C++ Namespace: simpleexample*Creating a namespacenamespace smallNamespace{int count = 0;void abc();} // end smallNamespaceUsing a namespacesmallNamesapce::count=0;usingnamespace smallNamespace;count +=1;abc(); 110
116.
C++ std namespace*Itemsdeclared in the C++ Standard Library are declared in the std namespaceYou include files for several functions declared in the std namespace To include input and output functions from the C++ library, write #include <iostream>usingnamespace std;111
117.
EncapsulationJust as acapsule protects its contents, the class construct protects its data members112// 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 ;} ;
Inheritance Inheritance: Amechanism used with a hierarchy of classes in which each descendant class inherits the properties (data and operations) of its ancestor class Base classThe class being inherited fromDerived classthe class that inherits114Inheritance is an "is-a" …
120.
Overriding & PolymorphismPolymorphism:the ability to determine which of several operations with the same name (within the class hierarchy) is appropriate, either at compiling time (static binding) or run time (dynamic binding)OverridingFunction with virtual keyword in base class.
An overridden functionin a derived class has the same signature and return type (i.e. prototype) as the function it overrides in its base class.115
123.
Example: Overriding116Each classhas a method PrintPerson.Print just prints the nameEmployee.Print prints the name and job titleManager.Print prints name, job title, and departmentPersonEmployeeManagerPrintis 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
124.
Object-Oriented ProgrammingInheritance andpolymorphism work together to allow programmer to build useful hierarchies of classes that can be put into a library to be reused in different applicationsExamples: 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
125.
Miscellaneous: I/O inC++Header files iostream and fstreamdeclare the istream, ostream,and ifstream, ofstream I/O classes.Both cin and cout are class objectsThese statements declare myInfile as an instance of class ifstream and invoke member function open. ifstream myInfile ; myInfile.open ( “A:\\mydata.dat” ) ;118