Object Oriented Programming with C Moshe Fresko BarIlan
Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007 -2008
Course Requirements n Goals n n Exercises n n To learn basics of Object Oriented Programming To program in C++ Practically see Design Paradigms Exercises will be 20% of the final grade Exam n 80% of the final grade
Resources n Books n n n C++ Programming Language, by Bjarne Stroustrup Thinking in C++, by Bruce Eckel C++ Professional in Hebrew Design Patterns, by Gamma, Helm, Johnson, and Vlissidis Compilers n n n Visual C++ Borland C++ GNU C++ (gcc)
Introduction to C++
History n n C++ is written by Bjarne Stroustrup from AT&T Bell Laboratories C++ is the extension into ANSI-C Procedural Programming Object Oriented Programming It supports n n n Object Oriented Programming Generic Programming etc.
History n 1980 1983 1985 1987 1989 n 1991 n 1995 n n n C with classes Name C++ is given Version 1. 0 (Basics) Standardization Process ANSI C++ Version 2. 0 (Multi-inheritance, Operator Overloading) Version 3. 0 (Templates) Standard Template Library (STL), namespace, RTTI C++ Design has been influenced from languages n Simula 67, Algol 68, and Small. Talk.
Introduction to C++ n Advantageous n n n Largely used Extension to C Object Oriented Programming Standard Template Library Efficient Programs can be written Disadvantageous n n n Complicated Language No support for Concurrent Programming No support for Serialization
Program Execution Language Translation n The translation of Human-Understandable Code into Machine. Understandable Two types of Translation n n 1. 2. Interpreter Compiler C++ Compilation Process n Preprocessor 1. Optionally also does Global Optimizations n Compiler 2. 1. 2. n First Pass: Creates parse tree Second Pass: Creates object modules (*. obj) Optionally also does Peephole Optimizations Linker 3. n From a list of Object Files creates an executable
Declaration vs. Definition n Declaration and Definition in C++ n Declaration: Introduces a name to the compiler. This name might be a user defined type, a variable, or a function. n Definition: It says make this function/variable here. It allocates storage for the name. n For any name many declarations can be done, but exactly one definition must exist.
Declaration vs. Definition n Functions n Definition int func 1(char, float) { /*…the code…*/ } n Declaration int func 1(char, float); n Variables n Definition int a ; n Declaration extern int a ;
Declaration vs. Definition // File: Exemple 1. cpp extern int i; // Declaration without definition extern float f(float); // Function declaration float b; // Declaration & definition float f(float a) { // Definition return a + 1. 0; } int i; // Definition int h(int x) { // Declaration & definition return x + 1; } int main() { b = 1. 0; i = 2; f(b); h(i); }
Header Files n A header file is a file containing the external declarations for a library. n It conventionally has a file name *. h. n To include a header file, use the #include preprocessor directive. n n n Search the file in “implementation-defined way. ” #include “local. h” Search the file in “include search path” #include <header> Old style vs. New Style Libraries #include <iostream. h> <iostream> <stdio. h> <cstdio>
Using Libraries n For using libraries 1. 2. 3. Include the library’s header file. Use the functions and variables in the library. Link the library into the executable program.
First C++ Program – Hello. cpp // Hello. cpp #include <iostream> //Stream declarations using namespace std; int main() { cout << "Hello, World! I am " << 8 << " Today!" << endl; } // To Compile: // // gcc Hello. cpp or g++ Hello. cpp or cl Hello. cpp
Some C++ Examples Number Conversion // Numconv. cpp // Converts decimal to octal and hex #include <iostream> using namespace std; int main() { int number; cout << "Enter a decimal number: "; cin >> number; cout << "value in octal = 0" << oct << number << endl; cout << "value in hex = 0 x" << hex << number << endl; }
Some C++ Examples string class // Hello. Strings. cpp // The basics of the Standard C++ string class #include <string> #include <iostream> using namespace std; int main() { string s 1, s 2; // Empty strings string s 3 = "Hello, World. "; // Initialized string s 4("I am"); // Also initialized s 2 = "Today"; // Assigning to a string s 1 = s 3 + " " + s 4; // Combining strings s 1 += " 8 "; // Appending to a string cout << s 1 + s 2 + "!" << endl; }
Some C++ Examples File Input Output // Scopy. cpp // Copy one file to another, a line at a time #include <string> #include <fstream> using namespace std; int main() { ifstream in(“File 1. txt"); // Open for reading ofstream out(“File 2. txt"); // Open for writing string s; while(getline(in, s)) // Discards newline char out << s << "n"; //. . . must add it back }
Some C++ Examples Fill String // Fill. String. cpp // Read an entire file into a single string #include <string> #include <iostream> #include <fstream> using namespace std; int main() { ifstream in(“File. txt”); string s, line; while(getline(in, line)) s += line + "n”; cout << s; }
Some C++ Examples vector class // Fillvector. cpp // Copy an entire file into a vector of string #include <string> #include <iostream> #include <fstream> #include <vector> using namespace std; int main() { vector<string> v; ifstream in("Fillvector. cpp"); string line; while(getline(in, line)) v. push_back(line); // Add the line to the end // Add line numbers: for(int i = 0; i < v. size(); i++) cout << i << ": " << v[i] << endl; }
Some C++ Examples vector with integers // Intvector. cpp // Creating a vector that holds integers #include <iostream> #include <vector> using namespace std; int main() { vector<int> v; for(int i = 0; i < 10; i++) v. push_back(i); for(int i = 0; i < v. size(); i++) cout << v[i] << ", "; cout << endl; for(int i = 0; i < v. size(); i++) v[i] = v[i] * 10; // Assignment for(int i = 0; i < v. size(); i++) cout << v[i] << ", "; cout << endl; }
Exercises 1. 2. 3. 4. 5. 6. 7. Using Numconv. cpp as guidelines, create a program that asks for the radius of a circle and prints the area of that circle. Create a program that opens a file and counts the whitespace-separated words in that file. Change Fillvector. cpp so that it prints the lines (backwards) from last to first. Display a file a line at a time, waiting for the user to press the “Enter” key after each line. Create a vector<float> and put 25 floating-point numbers into it using a for loop. Display the vector. Create three vector<float> objects and fill the first two as in the previous exercise. Write a for loop that adds each corresponding element in the first two vectors and puts the result in the corresponding element of the third vector. Display all three vectors. Create a vector<float> and put 25 numbers into it as in the previous exercises. Now square each number and put the result back into the same location in the vector. Display the vector before and after the multiplication.
Types and Declarations
Types and Declarations n Consider x = y + f(2) ; n To make it meaningful for C++ float x ; int y = 7 ; // // // float f(int) ; // argument // // x is a floating point variable y is an integer variable initialized to 7 f is a function taking type integer and returning floating point number
Fundamental Types n n Boolean Type bool Character Types such as char Integer Types such as int Floating-Point Types such as double n Absence of Information Type void n Enumeration Types enum n Pointer Types int* n Array Types char[] n Reference Types double& n Structures and Classes stru { … } class { … }
Booleans n bool is either true or false. n Examples: void f(int a, int b) { bool check = a==b ; // … } bool is_open(File*) ; bool greater(int a, int b) { return a>b ; } n Implicit Conversions n bool to int false 0 n int to bool 0 false true 1 Non-zero true
Character Types n char holds a character of implementation’s character n Example: n Two types set char ch = ‘a’ ; signed char unsigned char n -127 … 127 0 … 255 For Unicode wchar_t n Character Literals ‘a’ ‘ 0’ ‘n’ ‘t’ L’ab’
Integer Types n n n Three forms int signed int unsigned int Three sizes short int long int Integer Literals Decimal: Octal: Hexadecimal: ( or signed ) ( or unsigned ) ( or short ) ( or long ) 0 00 0 x 0 U for Unsigned Literals L for Long Literals 63 077 0 x 3 f 63 U 63 L
Floating Point Types n Three Sizes float double long double n Floating Point Literals 1. 23 1. 0 1. 2 e 10 Suffix F for float 0. 23 1. 23 e-15 3. 1416 f 1. 2. 0 F
Fundamental Types n sizeof(…) gives the size of any type in terms of chars sizeof(char) == 1 n Void void x ; void f() ; value void* pv ; // error // function does not return a // pointer to unknown type
Enumerations n n An enumeration is a type that can hold a set of values specified by the user. It is used like an integer type. Example: Or enum { ASM , AUTO , BREAK } ; // ASM==0, AUTO==1, BREAK==2 enum keyword { ASM , AUTO , BREAK } ; void f(keyword key) { switch(key) { case ASM : // do something break ; case BREAK : // do something break ; } }
Declarations and Definitions n Before an identifier can be used it must be declared (or defined), to inform the compiler what kind of entity the name refers char ch ; // NO VAL string s ; // NO VAL int count = 1 ; const double pi = 3. 1415926535897932385 ; extern int error_number ; // NO DEF char* name = “Haim” ; char* season [ ] = { “spring”, “summer”, “fall”, “winter” } ; struct Date { int d, m, y ; } ; int day(Date* p) { return p->d ; } double sqrt(double) ; // NO DEF template<class T> T abs(T a) { return a<0 ? –a : a ; } typedef complex<short> Point ; struct User ; // NO DEF enum Beer { Carlsberg, Tuborg, Macabi } ; namespace NS { int a; }
Declarations and Definitions n Some definitions do not have pre-declarations double sqrt(double) { /*…*/ } int error_number = 1 ; struct User { /*…*/ } n Declaring/Defining multiple names int* p, y; int x, *q; int v[10], *pv; n // int*p; int y; // int x; int*q; // int v[10]; int* pv; Name n Starts with letter or underscore and consists of letters, underscores and digits
Scope n A definition introduces a name into a scope. int x; // Global void f() { int x; // Local x hides global x x=1; // Assign to local x : : x=4; // Assign to global x { int x; // Hides previous local x x=2; // Assign to second local x } x=3; // Assign to first local x } int* p=&x; // Take address of global x
Initialization n Initialization int a ; // a is 0 double d ; void f() { int x ; } int arr[]={1, 2} Point z(1, 2) ; int f() ; n // x is not initialized ; // Array Initialization // Constructor Initialization // Function declaration lvalue : n n // d is 0. 0 Expression that refers to an object, that is modifiable. *p[a+10] = 7 ; Typedef : n Declares a new name typedef char* PChar ; PChar p 1, p 2 ;
Advices 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. Keep scopes small Don’t use the same name in both a scope and an enclosing scope Declare one name per declaration Keep common and local names short, and uncommon and non-local names longer Avoid similar-looking names Maintain a consistent naming style Choose names to reflect meaning rather then implementation Use a typedef to define a meaningful name for a built-in type in cases in which the built in type used to represent a value might change Use typedefs to define synonyms for types; use enumerations and classes to define new types Do not make assumptions on the size of integers/Objects Do not make assumptions on the range of floating-point types Avoid unsigned arithmetic View conversions with suspicion. Like signed to unsigned and vice verse, floating-point to integer, int to char, etc.
Pointers, Arrays, and Structures
Pointers n n n For a type T, T* is “pointer to T” A variable of type T* can hold the address of an object of type T. Example: char c = ‘a’ ; char* p = &c ; p: &c c // p holds the address of c: ‘a’
Pointers n Pointer Examples int* pi ; // pointer to int char** ppc ; // pointer to char int* ap[15] ; // array of 15 pointers to int (*fp)(char*) ; // pointer to function int* f(char*) ; // function n Dereferencing char c = ‘a’ ; char* p = &c ; // p holds the address of c char c 2 = *p ; // c 2 is assigned the value pointed by p n Zero NULL : const int NULL = 0 ;
Arrays n n n For a type T, T[size] is “array of size elements of T. ” Index from 0 to size-1. Examples float v[3] ; // array of 3 floats, v[0], v[1] and v[2] char* a[32] ; // array of 32 pointers to char void f(int i) { int v 1[i] ; // Error vector<int> v 2(i) ; // OK } int d 2[10][20] ; // Array of 10 arrays of 20 integers int v 1[] = {1, 2, 3, 4} ; char v 4[3] = {‘a’, ‘b’, 0}
Arrays n String Literals “this is a string” ; sizeof(“Arik”)==5 ; // const char[5], last char is ‘ ’ const char* error. Message() { /*…*/ return “Range-Error” ; } // Statically allocated cout << “End of the messagen” ; // New Line n Pointers into Arrays int v[]={1, 2, 3, 4} ; int* p 1 = v ; int* p 2 = &v[0] ; int* p 3 = &v[4] ; p 1 v: p 3 p 2 1 2 3 4
Arrays n Implicit conversion extern “C” int strlen(const char*); // from <string. h> void f() { char v[] = “Wonderful Life” ; char* p=v ; // Implicit conversion from char[] to char* strlen(p) ; strlen(v) ; // Implicit conversion from char[] to const char* // v = p ; // Error; Cannot assign into array } n Navigating Arrays void fi(char v[]) { for (int i=0; v[i]!=0; ++i) use(v[i]) ; } void fp(char v[]) { for (char* p=v; *p!=0; ++p) use(*p) ; }
Pointer Arithmetic n Pointer Address #include <iostream> int main() { int vi[10] ; short vs[10] ; std: : cout << &vi[0] << ‘ ‘ << &vi[1] << endl ; std: : cout << &vs[0] << ‘ ‘ << &vs[1] << endl ; } // Produces : 0 x 7 fffaef 0 0 x 7 fffaef 4 // 0 x 7 fffaedc 0 x 7 fffaede n Pointer Addition, Subraction void f() { int v 1[10] ; int v 2[10] ; int i 1 = &v 1[5]-&v 1[3] ; int i 2 = &v 1[5]-&v 2[3] ; int* p 1 = v 2+2; int* p 2 = v 2 -2 ; } // // 2 Result undefined p 1=&v 2[2] ; *p 2 is undefined
Constants n const values doesn’t change directly const int model=90 ; // model is a constant const int v[]={1, 2, 3} ; // v[i] is a constant const int x ; // Error: No Initializer void f() { model=200; // Error v[2]++ ; // Error } n const parameters void g(const X* p) { // can’t modify *p here } void h() { X val ; g(&val) ;
Pointers and Constants n Pointers involve two objects. The Value pointed to and the pointer. void f 1(char*p) { char s[]=“Mediterranean” ; const char* pc=s; // pointer to constant pc[3]=‘m’; // Error pc=p; // Ok char *const cp=s; // constant pointer cp[3]=‘m’; // Ok cp=p; // Error const char *const cpc=s; // const pointer to const cpc[3]=‘m’; // Error cpc=p; // Error }
References n A reference is an alternative name for an object. void f() { int i=1; int& r=i; int x=r; r=2; } void g() { int i=1; int& r=i; int* p=&r; r++; (*p)++; } // r and i refer to the same int // x is 1 // i is 2 // i is 3
References n Reference can be used as Copy-by-Reference argument to a function void increment ( int & a) { ++a ; } void incr ( int* p ) { ++(*p) ; } int next ( int i ) { return i+1 ; } void g() { int x = 1 ; increment (x) ; // x is 2 incr ( &x) ; // x is 3 x = next (x) ; // x is 4 }
Pointer to void n Any pointer can be assigned to void*, and void* can be explicitly converted to any pointer void f ( int* pi ) { void* pv = pi ; // implicit conversion *pv ; // error. Cannot dereference void* pv++ ; // error. Cannot increment void* int* pi 2 = static_cast<int*>(pv) ; // explicit conversion to int* double* pd 1=pv; // error double* pd 2=pi; // error double* pd 3=static_cast<double*>(pv); // unsafe } n Allocation into void* my_alloc(size_t n) ; // allocate n bytes from the heap
Structures n A struct is an aggregate of elements of arbitrary types. struct Address { char* name ; long int id ; char* street ; char* city ; long zip ; } // // // “Moshe Levy” 123456789 “Jabotinsky 33” “Ramat Gan” 34567 void f() { Address a ; a. name = “Moshe Levy” ; a. id = 123456789 ; } Address ad = { “Moshe Levy”, 123456789, “Jabotinsky 33”, “Ramat Gan”, 34567” }
Structures void print_addr ( Address* p ) { cout << p->name << “n” << p->id << “n” << p->street << “n” << p->town << “n” << p->zip << “n” ; } Address current ; Address set. Current ( Address next ) { Address prev = current ; current = next ; return prev ; }
Structures n The name is immediately available struct Link { Link *prev ; Link *next ; int value ; } struct No. Good { No. Good member ; // Error } n Pre Definition struct S ; extern S a ; S f() ; void g(S) ; void k(S* p) { Sa; f() ; p->m=7; S* q=h(p); } // // Error: Size needed to return a value Error: Member not known Ok
Advice 1. 2. 3. 4. 5. 6. 7. Avoid non-trivial Pointer Arithmetic Take care not to write beyond the bounds of an array Use vector instead of built in arrays Use string instead of ‘ ’ terminated char arrays Minimize use of plain reference arguments Avoid* except in low-level code Avoid non-trivial literals. Instead define and use symbolic constants.
A bit Background to C
Functions n Function Prototyping (Declaration) n The declaration of a function can be given in any place in the program int translate (float x, float y, float z); n In prototyping argument names are optional int translate (float, float); n Function definition n n The definition must be done only once. The argument names must be given since they are referenced inside the definition int translate (float x, float y, float z) { return x + y * z ; }
Functions n Return value type must be specified int f 1(void); // Returns an int, takes no arguments int f 2(); // Like f 1() in C++ float f 3(float, int, char, double); // Returns a float void f 4(void); // Takes no arguments, returns nothing n Return value must be returned in the definition // Return. cpp // Use of "return" #include <iostream> using namespace std; char cfunc(int i) { if(i == 0) return 'a'; return 'c'; } int main() { cout << "type an integer: "; int val; cin >> val; cout << cfunc(val) << endl; }
Parameter-Passing n Function Parameters n Pass-by-value: a copy of that argument is made inside the function // Pass. By. Value. cpp void f(int a) { a = 6; } int main() { int x = 48; f(x); int y = x; } n // x and y are 48 Pass-by-reference: An alias of the passed name // Pass. By. Value. cpp void f(int& a) { a = 6; } int main() { int x = 48; f(x); int y = x; // x and y are 6 }
Parameter-Passing Examples n We can pass-by-reference effect by passing pointer // Pass. By. Pointer. cpp void f(int* a) { *a = 6; } int main() { int x = 48; f(&x); int y = x; // x and y are 6 } n Some Examples n n void f 1(char c, int i, float f, double d); f 2(short int si, long int li, long double ld); f 3(char* cp, int* ip, float* fp, double* dp); f 4(char& cr, int& ir, float& fr, double& dr);
Control Statements n C++ Control Statements n n n if-else while do-while for switch goto
Control Statements if-else if(expression) statement OR if(expression) statement else statement n n Expression must evaluate to true or false Statement must be in { } in case it has more then once command
Control Statements - if-else // Ifthen. cpp // Demonstration of if and if-else conditionals #include <iostream> using namespace std; int main() { int i; cout << "type a number and 'Enter'" << endl; cin >> i; if(i > 5) cout << "It's greater than 5" << endl; else if(i < 5) cout << "It's less than 5 " << endl; else cout << "It's equal to 5 " << endl; }
Control Statements - while n The statement is repeated until the expression is false while (expression) statement n n The expression is evaluated once at the beginning of the loop and again before each further iteration of the statement Example // Guess. cpp // Guess a number (demonstrates "while") #include <iostream> using namespace std; int main() { int secret = 15; int guess = 0; while (guess != secret) { // Compound statement cout << "guess the number: "; cin >> guess; } cout << "You guessed it!" << endl; }
Control Statements – do-while do statement while (expression); n n The expression is evaluated after the first loop if it is true the next iteration is done before checking it again Example n // Guess 2. cpp // The guess program using do-while #include <iostream> using namespace std; int main() { int secret = 15; int guess; // No initialization needed here do { cout << "guess the number: "; cin >> guess; // Initialization happens } while (guess != secret); cout << "You got it!" << endl; }
Control Statements - for n n for ( initialization; conditional; step) statement The initialization code executes once at the very beginning. The conditional is tested before each iteration (if it evaluates to false at the beginning, the statement never executes). At the end of each loop, the step executes. Example: n // Charlist. cpp // Display all the ASCII characters // Demonstrates "for" #include <iostream> using namespace std; int main() { for ( int i = 0; i < 128; i = i + 1) if (i != 26) // ANSI Terminal Clear screen cout << " value: " << i << " character: " << char(i) << endl; }
Control Statements break and continue statements n n n break quits the loop without executing the rest of the statements in the loop. continue stops the execution of the current iteration and goes back to the beginning of the loop to begin a new iteration. Example // Menu. cpp // Simple menu program demonstrating the use of "break" and "continue" #include <iostream> using namespace std; int main() { char c; // To hold response while(true) { cout << "MAIN MENU: " << endl << “l: left, r: right, q: quit -> "; cin >> c; if(c == 'q') break; if(c == 'l') { /* … Do something … */ continue; } if(c==‘r’) { /* … Do something … */ continue ; } cout << “Error!” << endl ; } }
Control Statements - switch n A switch statement selects from among pieces of code switch(selector) { case integral-value 1 : statement; break; case integral-value 2 : statement; break; case integral-value 3 : statement; break; (. . . ) default: statement; }
Control Statements - switch //: C 03: Menu 2. cpp // A menu using a switch statement #include <iostream> using namespace std; int main() { bool quit = false; // Flag for quitting while(quit == false) { cout << "Select a, b, c or q to quit: "; char response; cin >> response; switch(response) { case 'a' : cout << "you chose 'a'" << endl; break; case 'b' : cout << "you chose 'b'" << endl; break; case 'c' : cout << "you chose 'c'" << endl; break; case 'q' : cout << "quitting menu" << endl; quit = true; break; default : cout << "Please use a, b, c or q!" << endl; } } }
Auto-Increment/Decrement n n n ++i i++ --i i-Example increments i and returns the new value increments i and returns the previous values decrements i and returns the new value decrements i and returns the previous value // Auto. Increment. cpp // Shows use of auto-increment and auto-decrement operators. #include <iostream> using namespace std; int main() { int i = 0; int j = 0; cout << ++i << endl; // Pre-increment prints cout << j++ << endl; // Post-increment cout << --i << endl; // Pre-decrement cout << j-- << endl; // Post decrement }
Scoping n The variables are available within their scope from the point they are defined. void main() { // no variables int i 1 ; // i 1 is available here { // i 1 is available here, but not i 2 int i 2 ; // i 1 and i 2 are available here } // i 1 is available here but not i 2 }
Dynamic Object Creation
Dynamic Object Creation n Not always we know the exact quantity, type, and lifetime of the objects in a program. We need to create and destroy objects at runtime. n Dynamic Memory allocation in C n n n void* malloc(int size); void* calloc(int num, int size); void* realloc(void*, int size); void free(void*); n These methods allocates/frees blocks of memory on the heap n This will not work in C++ for Objects, since n n n One can forget to initialize the object One can accidentally do something to the object before it is initialized Hand it the wrong-sized object.
C’s approach for Memory Allocation in C++ // Malloc. Class. cpp // Malloc with class objects. What you'd have to do if not for "new“. #include <cstdlib> // malloc() & free() #include <iostream> using namespace std; class Obj { void initialize() // Can't use constructor { cout << "initializing Obj" << endl; } void destroy() const // Can't use destructor { cout << "destroying Obj" << endl; } }; int main() { Obj* obj = (Obj*)malloc(sizeof(Obj)); obj->initialize(); //. . . sometime later: obj->destroy(); free(obj); }
Dynamic Object Creation n When a C++ object is created 1. 2. n Storage is allocated for the object. The constructor is called to initialize that storage. Storage can be allocated n n n Before the program begins, in the static storage area. Storage can be created on the stack Storage can be allocated from the heap
Dynamic Object Creation n Dynamic Memory allocation in C++ n Allocating one object with new operator n My. Type *fp = new My. Type; // Default Constructor n My. Type *fp = new My. Type(1, ’a’); // Another constructor n n Freeing one object with delete operator n delete fp; Allocating an array of objects with new[] operator n My. Type* fparr = new My. Type[100]; // Only Default Constructor n Freeing a list of objects with delete[] operator n delete[] fparr;
Dynamic Object Creation Example // Stack. h // Stack: LIFO: It allows to insert and to get numbers in // The number to be get next is the one inserted more recently class Stack { private: int* arr ; // The list of numbers is kept here int size ; // The size of the numbers in the stack int capacity ; // The capacity of the array void resize() ; public: Stack() { size=0; capacity=10; arr=new int[capacity] ; } ~Stack() { delete [] arr ; } void put(int next) ; int get() ; bool is. Empty() { return size==0 ; } };
Dynamic Object Creation Example // Stack. cpp : The definitions for some functions of Stack void Stack: : put(int next) { if (size==capacity) resize() ; arr[size++] = next ; } int Stack: : get() { return arr[--size] ; } void Stack: : resize() { capacity *= 2 ; int* narr = new int[capacity] ; for (int i=0; i<size; ++i) *(narr+i) = *(arr+i) ; delete [] arr ; arr = narr ; }
Dynamic Object Creation Example // Stack. Usage. cpp // Trying the Stack Class #include <iostream> using namespace std; int main() { Stack stack; stack. put(10) ; stack. put(20) ; stack. put(30) ; while (! stack. is. Empty()) cout << “The next number get: “ << stack. get() << endl ; } // Prints in order: 30, 20, and 10
Exercises 1. 2. Write class Queue. It will work as a FIFO. The element will exit in the same order they are inserted. Write class String that can grow infinitely. It will have a default ctor will start with an empty internal string. Function append(const char*) adds the given string into the end of the internal string. Reminder: The string in C is a character array ending with ‘ ’.
- Slides: 76