Final Touches MultipleFile Programs Inheritance Templates MultipleFile Programs

  • Slides: 25
Download presentation
Final Touches: Multiple-File Programs, Inheritance, Templates • Multiple-File Programs – header files – implementation

Final Touches: Multiple-File Programs, Inheritance, Templates • Multiple-File Programs – header files – implementation files – main-program file) • Inheritance in C++ • Templates in C++ CS 103 1

Why Multiple Files • Re-use • Better data abstraction (data hiding) • More manageability

Why Multiple Files • Re-use • Better data abstraction (data hiding) • More manageability of large programs CS 103 2

The Multiple-File Approach • Have each major class as a separate program – Re-use:

The Multiple-File Approach • Have each major class as a separate program – Re-use: The class can then be used by other programs using the #include macro instead of the copy-&-paste approach • Put the class/function declarations in a header (. h) file, and the class/function implementations in another (. c or. cpp) file. This achieves data hiding. CS 103 3

Example Stack. h file: class Stack { public: typedef int dtype; Stack(int cap=100); int

Example Stack. h file: class Stack { public: typedef int dtype; Stack(int cap=100); int get. Capacity(); void push(dtype b); dtype pop(); dtype peek(); bool is. Empty(); private: dtype *dataptr; int top; int capacity; }; Stack. cpp file: #include "Stack. h" Stack: : Stack(int cap){ top=0; capacity = (cap>0)? cap: 100; dataptr = new int[capacity]; }; int Stack: : get. Capacity( ) { return capacity; }; int Stack: : dtype Stack: : pop(){ assert(!is. Empty()); return dataptr[--top]; }; // the implementation of // the remaining methods. . . . CS 103 Project 1. cpp file: #include <cstdlib> #include <iostream> #include "Stack. h” using namespace std; // local stuff, if any int main(int argc, char *argv[]){ ……… } 4

What should Go into a. h File • Only declarations (i. e. , info

What should Go into a. h File • Only declarations (i. e. , info to the compiler) • Nothing that requires storage • Reason: – a header file gets included in several files of a project; – if storage for a variable (or for a code) is allocated multiple times, you get a multiple-definition compilation error • Advanced: One exception to this rule is static data (data local to a file), because the linker does not allocate multiple instances to static data. CS 103 5

Redeclarations Issues • An X. h file can have: #include “Y. h” • Consider

Redeclarations Issues • An X. h file can have: #include “Y. h” • Consider this scenario: – The X. h file has: #include “Y. h” #include “Z. h” – The Y. h file has: #include “Z. h” – This means: the declarations in Z. h are included twice in X. h. The second declarations are called redeclarations • Class redeclarations are not allowed. • So, we have a problem CS 103 6

Redeclarations Issue Solution • Inside each Z. h file, do: – Add to at

Redeclarations Issue Solution • Inside each Z. h file, do: – Add to at the start of the file (right after all the #includes) the next two lines: #ifndef Z_H_ #define Z_H_ // Not that Z is the name of. h file – Add the following line at the very end of Z. h (on a separate line): #enddef CS 103 7

Class Inheritance in C++ • Inheritance allows us to create new classes which are

Class Inheritance in C++ • Inheritance allows us to create new classes which are derived from older classes Notation: base – The derived classes are called subclasses or simply derived classes subclass 1 subclass 2 – The older classes are superclasses or parent classes or base classes • A derived class automatically includes some of its parent's members, and can have additional ones. CS 103 8

Conceptual Examples of Hierarchical Classes Animal Reptile Person Bird Man Woman Father Mother Lawyer

Conceptual Examples of Hierarchical Classes Animal Reptile Person Bird Man Woman Father Mother Lawyer Student Engineer Grad CS 103 UG 9

Syntax for Inheritance class derived. Class : public base. Class { private : //

Syntax for Inheritance class derived. Class : public base. Class { private : // Declarations of additional members, if needed. public: // Declarations of additional members, if needed. protected: // Declarations of additional members, if needed. } The derived class inherits from the base class: all public members, all protected members (see later), and the default constructor The additional members defined can have the same name (and type) as those of the base class (as when some base members are to be redefined) CS 103 10

“Protected” Access • We have seen two access modes in C++ classes: public and

“Protected” Access • We have seen two access modes in C++ classes: public and private – Public members are directly accessible by users of the class – Private members are NOT directly accessible by users of the class, not even by inheritors • There is a 3 rd access mode: protected – Protected members are directly accessible by derived classes but not by other users CS 103 11

Example of Inherited Classes class Shape { class Triangle: public Shape { protected: public:

Example of Inherited Classes class Shape { class Triangle: public Shape { protected: public: int width, height; int area ( ) { public: return (width * height/2); void set. Dims (int a, int b){ } width=a; height=b; } }; }; class Rectangle: public Shape { class Square: public Rectangle { public: int area ( ) { void set. Dims (int a){ return (width * height); width=a; height=a; } } }; }; CS 103 12

Another Example of Inherited Classes (A char stack inherited from string) class Char. Stack:

Another Example of Inherited Classes (A char stack inherited from string) class Char. Stack: public string{ public: void push(char b){ string str; str += b; insert(0, str); }; char peek( ){return at(0); }; char pop( ){ char a=at(0); erase(0, 1); return a; }; // size( ) and empty( ) are the // same in string, so are // inherited as is. } CS 103 Observations: • We have no idea how the string class is implemented, and we don’t care • Char. Stack inherited from string all the latter’s public methods, including size( ) and empty( ) • We implemented push( ), pop( ) and peek( ) using the public methods of the string class 13

More on Inheritance Syntax class derived. Class : protected base. Class { …}; //

More on Inheritance Syntax class derived. Class : protected base. Class { …}; // Effect: all public members inherited from base. Class are // now protected members of derived. Class class derived. Class : private base. Class { …}; // Effect: all public and protected members inherited from // base. Class are now private members of derived. Class Multiple inheritance A class can inherit several classes at once: class derived. Class: public base. Class 1, public base. Class 2{ …}; Remark: Not recommended CS 103 14

Templates • We saw function templates early on • Templates allow us to turn

Templates • We saw function templates early on • Templates allow us to turn the type of data into a parameter that can be changed at will • For example, we defined stacks/queues/trees of ints – If we want a stack/queues/trees of floats, we have to cut and paste, and change the data type from int to float – We reduced this effort by using: typedef int datatype; – That is still inconvenient, time-consuming, and error prone – With templates, we do not need to cut+paste+change CS 103 15

Function Templates (Reminder ) • Syntax for declaring a function template: template<class type> function_declaration;

Function Templates (Reminder ) • Syntax for declaring a function template: template<class type> function_declaration; -Ortemplate<typename type> function_declaration; Example of a Function Template Declaration: // Returns the minimum of array x[ ]. The data // type of x[ ] is arbitrary & customizable template<typename T> T min(T x[], int length){ T m = x[0]; // M is the minimum so far for (int i=1; i<n; i++) if (x[i]<m) m=x[i]; return m; } CS 103 Example of Use: int x[]= {11, 13, 5, 7, 4, 10}; double y[]= {4. 5, 7. 13, 17}; int minx = min<int>(x, 6); double miny= min<double>(y, 3); 16

Templates with More than One Generic Type • Templates can have several generic types

Templates with More than One Generic Type • Templates can have several generic types • Syntax for their declaration: template<class type 1, class type 2> funct_decl; • class can be replaced by typename. CS 103 17

Class Templates • Much as function templates allow argument types to be parameterized, class

Class Templates • Much as function templates allow argument types to be parameterized, class templates allow us to parameterize the types of: – member variables – arguments of member functions & constructors – return values of member functions • The syntax is similar but somewhat more cumbersome CS 103 18

Class Templates Syntax • For class template declaration: template<class T> class_declaration; • For the

Class Templates Syntax • For class template declaration: template<class T> class_declaration; • For the implementation of the methods outside the class, the syntax is: template<class T> return_type class. Name<T>: : method. Name(parameter-list){ ……} • For the implementation of the constructors outside the class, the syntax is: template<class T> class. Name<T>: : class. Name(parameter-list){……} CS 103 19

Stack as a Class Template template <class T> class stack { private : T

Stack as a Class Template template <class T> class stack { private : T *dataptr; int top; int capacity; public: stack(int cap=100); int get. Capacity() {return capacity; } void push(T b); T pop() {assert(top>0); return dataptr[--top]; } bool is. Empty() {return top==0; } }; CS 103 20

template<class T> stack<T>: : stack(int cap){ top=0; capacity = (cap>0)? cap: 100; dataptr =

template<class T> stack<T>: : stack(int cap){ top=0; capacity = (cap>0)? cap: 100; dataptr = new T[capacity]; } template<class T> void stack<T>: : push(T b){ if (top < capacity) dataptr[top++]=b; else{ capacity *=2; T *newptr=new T[capacity]; for(int k=0; k<capacity/2; k++) newptr[k]=dataptr[k]; delete [] dataptr; dataptr = newptr; dataptr[top++]=b; } } CS 103 21

A Complete Program Using a Stack Template #include <cstdlib> #include <iostream> using namespace std;

A Complete Program Using a Stack Template #include <cstdlib> #include <iostream> using namespace std; // template stack definition goes here int main(int argc, char *argv[]){ stack<int> int. S(5); // a stack of integers cout<<"int. S capacity after construction = "<<int. S. get. Capacity()<<endl; int x[]={2, 3, 7, 8, -10, 14, 5}; for (int i=0; i<7; i++) int. S. push(x[i]); cout<<"int. S capacity after pushing 7 elements="<< int. S. get. Capacity(); cout<<“n. Emptying int. S: "; while (!int. S. is. Empty()) cout<<int. S. pop()<<"; "; cout<<endl; CS 103 22

stack<char *> string. S(5); // a stack of strings string. S. push("hi"); string. S.

stack<char *> string. S(5); // a stack of strings string. S. push("hi"); string. S. push("there"); cout<<"Emptying string. S: "; while (!string. S. is. Empty()) cout<<string. S. pop()<<"; "; cout<<endl; double y[]={3. 14, 9. 8, 1. 42, 12}; stack<double> double. S(y, 4); // a stack of doubles cout<<"double. S capacity="<<double. S. get. Capacity()<<endl; cout<<"Emptying double. S: "; while (!double. S. is. Empty()) cout<<double. S. pop()<<"; "; cout<<endl; } CS 103 23

C++ Standard Templates Library (STL) • C++ comes with a library that supports most

C++ Standard Templates Library (STL) • C++ comes with a library that supports most of the data structures (i. e. , classes) we covered in this semester Class What to Include stack #include <stack> queue #include <queue> list #include <list> heap #include <heap> set #include <set> vector #include <vector> CS 103 24

Some Operations of STL Classes stack // constructor stack<T> s; //T is any built-in

Some Operations of STL Classes stack // constructor stack<T> s; //T is any built-in or user-defined type void push (T a) void pop( ); // deletes top element. T top( ); // like peek(). int size( ); // returns # elements in s bool empty(); // // true if s is empty queue // constructor queue<T> q; T front( ); //returns front value T back( ); //returns back value void push (T a); // enqueue void pop( ); //dequeue int size( ); // returns # elements in q bool empty(); // true if q is empty CS 103 25