SlideShare a Scribd company logo
1
Multiple-File Programs,
Inheritance, Templates
•Multiple-File Programs
• header files
• implementation files
• main-program file)
•Inheritance in C++
•Templates in C++
2
Why Multiple Files
• Re-use
• Better data abstraction (data hiding)
• More manageability of large programs
3
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.
4
Example
class Stack {
public:
typedef int dtype;
Stack(int cap=100);
int getCapacity();
void push(dtype b);
dtype pop();
dtype peek();
bool isEmpty();
private:
dtype *dataptr;
int top;
int capacity;
};
#include "Stack.h"
Stack::Stack(int cap){
top=0;
capacity = (cap>0)?cap:100;
dataptr = new int[capacity];
};
int Stack::getCapacity( ) {
return capacity;
};
int Stack::dtype Stack::pop(){
assert(!isEmpty());
return dataptr[--top];
};
// the implementation of
// the remaining methods
........
#include <cstdlib>
#include <iostream>
#include "Stack.h”
using namespace std;
// local stuff, if any
int main(int argc,
char *argv[]){
………
}
Stack.h file: Stack.cpp file: Project1.cpp file:
5
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.
6
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
7
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_ // Not that Z is the name of .h file
#define Z_H_
• Add the following line at the very end of Z.h (on a separate line):
#enddef
8
Class Inheritance in C++
• Inheritance allows us to create new classes which are derived from
older classes
• The derived classes are
called subclasses or simply
derived classes
• 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.
base
subclass1 subclass2
Notation:
9
Conceptual Examples of Hierarchical
Classes
Animal
PersonReptile Bird
Man Woman
Person
StudentLawyer Engineer
Grad UG
MotherFather
10
Syntax for Inheritance
class derivedClass : public baseClass {
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)
11
“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 3rd access mode: protected
• Protected members are directly accessible by derived classes but not by other
users
12
Example of Inherited Classes
class Shape {
protected:
int width, height;
public:
void setDims (int a, int b){
width=a; height=b;}
};
class Rectangle: public Shape {
public:
int area ( ) {
return (width * height);
}
};
class Triangle: public Shape {
public:
int area ( ) {
return (width * height/2);
}
};
class Square: public Rectangle {
public:
void setDims (int a){
width=a; height=a;}
};
13
Another Example of Inherited Classes
(A char stack inherited from string)
class CharStack: 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.
}
Observations:
• We have no idea how
the string class is
implemented, and we
don’t care
• CharStack 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
14
More on Inheritance Syntax
class derivedClass : protected baseClass { …};
// Effect: all public members inherited from baseClass are
// now protected members of derivedClass
class derivedClass : private baseClass { …};
// Effect: all public and protected members inherited from
// baseClass are now private members of derivedClass
Multiple inheritance A class can inherit several classes
at once:
class derivedClass:public baseClass1,public baseClass2{ …};
Remark: Not recommended
15
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
16
Function Templates (Reminder )
• Syntax for declaring a function template:
template<class type> function_declaration;
-Or-
template<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;
}
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);
17
Templates with More than One Generic Type
• Templates can have several generic types
• Syntax for their declaration:
• class can be replaced by typename.template<class type1,class type2> funct_decl;
18
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
19
Class Templates Syntax
• For class template declaration:
• For the implementation of the methods outside the class, the syntax
is:
• For the implementation of the constructors outside the class, the
syntax is:
template<class T> class_declaration;
template<class T> return_type className<T>::methodName(parameter-list){
……}
template<class T> className<T>:: className(parameter-list){……}
20
template <class T> class stack {
private :
T *dataptr;
int top;
int capacity;
public:
stack(int cap=100);
int getCapacity() {return capacity;}
void push(T b);
T pop() {assert(top>0); return dataptr[--top];}
bool isEmpty() {return top==0;}
};
Stack as a Class Template
21
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;
}
}
22
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> intS(5); // a stack of integers
cout<<"intS capacity after construction = "<<intS.getCapacity()<<endl;
int x[]={2,3,7,8,-10,14,5};
for (int i=0;i<7;i++)
intS.push(x[i]);
cout<<"intS capacity after pushing 7 elements="<< intS.getCapacity();
cout<<“nEmptying intS: ";
while (!intS.isEmpty())
cout<<intS.pop()<<"; ";
cout<<endl;
23
stack<char *> stringS(5); // a stack of strings
stringS.push("hi");
stringS.push("there");
cout<<"Emptying stringS: ";
while (!stringS.isEmpty())
cout<<stringS.pop()<<"; ";
cout<<endl;
double y[]={3.14,9.8,1.42,12};
stack<double> doubleS(y,4); // a stack of doubles
cout<<"doubleS capacity="<<doubleS.getCapacity()<<endl;
cout<<"Emptying doubleS: ";
while (!doubleS.isEmpty())
cout<<doubleS.pop()<<"; ";
cout<<endl;
}
24
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>
25
Some Operations of STL Classes
stack queue
// 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
// 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

More Related Content

What's hot

AGGREGATE FUNCTION.pptx
AGGREGATE FUNCTION.pptxAGGREGATE FUNCTION.pptx
AGGREGATE FUNCTION.pptx
Anusha sivakumar
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
Farooq Baloch
 
Lexical analysis - Compiler Design
Lexical analysis - Compiler DesignLexical analysis - Compiler Design
Lexical analysis - Compiler Design
Muhammed Afsal Villan
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKumar
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
Neeru Mittal
 
Cursors
CursorsCursors
Templates in c++
Templates in c++Templates in c++
Templates in c++
ThamizhselviKrishnam
 
String c
String cString c
Machine language
Machine languageMachine language
Machine language
鍾誠 陳鍾誠
 
Summer Training Project On C++
Summer Training Project On  C++Summer Training Project On  C++
Summer Training Project On C++
KAUSHAL KUMAR JHA
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
Math-Circle
 
C programming
C programmingC programming
C programming
Rounak Samdadia
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File
Harjinder Singh
 
VTU Data Structures Lab Manual
VTU Data Structures Lab ManualVTU Data Structures Lab Manual
VTU Data Structures Lab Manual
Nithin Kumar,VVCE, Mysuru
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
Vikram Nandini
 
Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & Deletion
Afaq Mansoor Khan
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
Sandeep Rawat
 

What's hot (20)

AGGREGATE FUNCTION.pptx
AGGREGATE FUNCTION.pptxAGGREGATE FUNCTION.pptx
AGGREGATE FUNCTION.pptx
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Lexical analysis - Compiler Design
Lexical analysis - Compiler DesignLexical analysis - Compiler Design
Lexical analysis - Compiler Design
 
Mysql
MysqlMysql
Mysql
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Loaders
LoadersLoaders
Loaders
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Cursors
CursorsCursors
Cursors
 
Sql queries
Sql queriesSql queries
Sql queries
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
String c
String cString c
String c
 
Machine language
Machine languageMachine language
Machine language
 
Summer Training Project On C++
Summer Training Project On  C++Summer Training Project On  C++
Summer Training Project On C++
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
C programming
C programmingC programming
C programming
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File
 
VTU Data Structures Lab Manual
VTU Data Structures Lab ManualVTU Data Structures Lab Manual
VTU Data Structures Lab Manual
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & Deletion
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 

Similar to Multiple file programs, inheritance, templates

Templates2
Templates2Templates2
Templates2
zindadili
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Inheritance
InheritanceInheritance
Inheritance
Mustafa Khan
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
rehan16091997
 
Inheritance
Inheritance Inheritance
Inheritance
Parthipan Parthi
 
OOP
OOPOOP
TEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented ProgrammingTEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented Programming
208BVijaySunder
 
Lecture 24 multiple-fileprograming.pptx
Lecture 24 multiple-fileprograming.pptxLecture 24 multiple-fileprograming.pptx
Lecture 24 multiple-fileprograming.pptx
AyeCS11
 
3 functions and class
3   functions and class3   functions and class
3 functions and classtrixiacruz
 
UNIT3 on object oriented programming.pptx
UNIT3 on object oriented programming.pptxUNIT3 on object oriented programming.pptx
UNIT3 on object oriented programming.pptx
urvashipundir04
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
Michael Heron
 
c++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfc++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdf
nisarmca
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.ppt
BArulmozhi
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
Renas Rekany
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classDeepak Singh
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)
ProCharm
 

Similar to Multiple file programs, inheritance, templates (20)

Templates2
Templates2Templates2
Templates2
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
Inheritance
InheritanceInheritance
Inheritance
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Inheritance
Inheritance Inheritance
Inheritance
 
OOP
OOPOOP
OOP
 
Bc0037
Bc0037Bc0037
Bc0037
 
TEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented ProgrammingTEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented Programming
 
Lecture 24 multiple-fileprograming.pptx
Lecture 24 multiple-fileprograming.pptxLecture 24 multiple-fileprograming.pptx
Lecture 24 multiple-fileprograming.pptx
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
UNIT3 on object oriented programming.pptx
UNIT3 on object oriented programming.pptxUNIT3 on object oriented programming.pptx
UNIT3 on object oriented programming.pptx
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
Basics of objective c
Basics of objective cBasics of objective c
Basics of objective c
 
c++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfc++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdf
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.ppt
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-class
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)
 

More from Syed Zaid Irshad

Operating System.pdf
Operating System.pdfOperating System.pdf
Operating System.pdf
Syed Zaid Irshad
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
Syed Zaid Irshad
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
Syed Zaid Irshad
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
Syed Zaid Irshad
 
Professional Issues in Computing
Professional Issues in ComputingProfessional Issues in Computing
Professional Issues in Computing
Syed Zaid Irshad
 
Reduce course notes class xi
Reduce course notes class xiReduce course notes class xi
Reduce course notes class xi
Syed Zaid Irshad
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
Syed Zaid Irshad
 
Introduction to Database
Introduction to DatabaseIntroduction to Database
Introduction to Database
Syed Zaid Irshad
 
C Language
C LanguageC Language
C Language
Syed Zaid Irshad
 
Flowchart
FlowchartFlowchart
Flowchart
Syed Zaid Irshad
 
Algorithm Pseudo
Algorithm PseudoAlgorithm Pseudo
Algorithm Pseudo
Syed Zaid Irshad
 
Computer Programming
Computer ProgrammingComputer Programming
Computer Programming
Syed Zaid Irshad
 
ICS 2nd Year Book Introduction
ICS 2nd Year Book IntroductionICS 2nd Year Book Introduction
ICS 2nd Year Book Introduction
Syed Zaid Irshad
 
Security, Copyright and the Law
Security, Copyright and the LawSecurity, Copyright and the Law
Security, Copyright and the Law
Syed Zaid Irshad
 
Computer Architecture
Computer ArchitectureComputer Architecture
Computer Architecture
Syed Zaid Irshad
 
Data Communication
Data CommunicationData Communication
Data Communication
Syed Zaid Irshad
 
Information Networks
Information NetworksInformation Networks
Information Networks
Syed Zaid Irshad
 
Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information Technology
Syed Zaid Irshad
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year Book
Syed Zaid Irshad
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
Syed Zaid Irshad
 

More from Syed Zaid Irshad (20)

Operating System.pdf
Operating System.pdfOperating System.pdf
Operating System.pdf
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
Professional Issues in Computing
Professional Issues in ComputingProfessional Issues in Computing
Professional Issues in Computing
 
Reduce course notes class xi
Reduce course notes class xiReduce course notes class xi
Reduce course notes class xi
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
Introduction to Database
Introduction to DatabaseIntroduction to Database
Introduction to Database
 
C Language
C LanguageC Language
C Language
 
Flowchart
FlowchartFlowchart
Flowchart
 
Algorithm Pseudo
Algorithm PseudoAlgorithm Pseudo
Algorithm Pseudo
 
Computer Programming
Computer ProgrammingComputer Programming
Computer Programming
 
ICS 2nd Year Book Introduction
ICS 2nd Year Book IntroductionICS 2nd Year Book Introduction
ICS 2nd Year Book Introduction
 
Security, Copyright and the Law
Security, Copyright and the LawSecurity, Copyright and the Law
Security, Copyright and the Law
 
Computer Architecture
Computer ArchitectureComputer Architecture
Computer Architecture
 
Data Communication
Data CommunicationData Communication
Data Communication
 
Information Networks
Information NetworksInformation Networks
Information Networks
 
Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information Technology
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year Book
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
 

Recently uploaded

Steel & Timber Design according to British Standard
Steel & Timber Design according to British StandardSteel & Timber Design according to British Standard
Steel & Timber Design according to British Standard
AkolbilaEmmanuel1
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
Kamal Acharya
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 

Recently uploaded (20)

Steel & Timber Design according to British Standard
Steel & Timber Design according to British StandardSteel & Timber Design according to British Standard
Steel & Timber Design according to British Standard
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 

Multiple file programs, inheritance, templates

  • 1. 1 Multiple-File Programs, Inheritance, Templates •Multiple-File Programs • header files • implementation files • main-program file) •Inheritance in C++ •Templates in C++
  • 2. 2 Why Multiple Files • Re-use • Better data abstraction (data hiding) • More manageability of large programs
  • 3. 3 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.
  • 4. 4 Example class Stack { public: typedef int dtype; Stack(int cap=100); int getCapacity(); void push(dtype b); dtype pop(); dtype peek(); bool isEmpty(); private: dtype *dataptr; int top; int capacity; }; #include "Stack.h" Stack::Stack(int cap){ top=0; capacity = (cap>0)?cap:100; dataptr = new int[capacity]; }; int Stack::getCapacity( ) { return capacity; }; int Stack::dtype Stack::pop(){ assert(!isEmpty()); return dataptr[--top]; }; // the implementation of // the remaining methods ........ #include <cstdlib> #include <iostream> #include "Stack.h” using namespace std; // local stuff, if any int main(int argc, char *argv[]){ ……… } Stack.h file: Stack.cpp file: Project1.cpp file:
  • 5. 5 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.
  • 6. 6 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
  • 7. 7 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_ // Not that Z is the name of .h file #define Z_H_ • Add the following line at the very end of Z.h (on a separate line): #enddef
  • 8. 8 Class Inheritance in C++ • Inheritance allows us to create new classes which are derived from older classes • The derived classes are called subclasses or simply derived classes • 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. base subclass1 subclass2 Notation:
  • 9. 9 Conceptual Examples of Hierarchical Classes Animal PersonReptile Bird Man Woman Person StudentLawyer Engineer Grad UG MotherFather
  • 10. 10 Syntax for Inheritance class derivedClass : public baseClass { 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)
  • 11. 11 “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 3rd access mode: protected • Protected members are directly accessible by derived classes but not by other users
  • 12. 12 Example of Inherited Classes class Shape { protected: int width, height; public: void setDims (int a, int b){ width=a; height=b;} }; class Rectangle: public Shape { public: int area ( ) { return (width * height); } }; class Triangle: public Shape { public: int area ( ) { return (width * height/2); } }; class Square: public Rectangle { public: void setDims (int a){ width=a; height=a;} };
  • 13. 13 Another Example of Inherited Classes (A char stack inherited from string) class CharStack: 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. } Observations: • We have no idea how the string class is implemented, and we don’t care • CharStack 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
  • 14. 14 More on Inheritance Syntax class derivedClass : protected baseClass { …}; // Effect: all public members inherited from baseClass are // now protected members of derivedClass class derivedClass : private baseClass { …}; // Effect: all public and protected members inherited from // baseClass are now private members of derivedClass Multiple inheritance A class can inherit several classes at once: class derivedClass:public baseClass1,public baseClass2{ …}; Remark: Not recommended
  • 15. 15 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
  • 16. 16 Function Templates (Reminder ) • Syntax for declaring a function template: template<class type> function_declaration; -Or- template<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; } 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);
  • 17. 17 Templates with More than One Generic Type • Templates can have several generic types • Syntax for their declaration: • class can be replaced by typename.template<class type1,class type2> funct_decl;
  • 18. 18 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
  • 19. 19 Class Templates Syntax • For class template declaration: • For the implementation of the methods outside the class, the syntax is: • For the implementation of the constructors outside the class, the syntax is: template<class T> class_declaration; template<class T> return_type className<T>::methodName(parameter-list){ ……} template<class T> className<T>:: className(parameter-list){……}
  • 20. 20 template <class T> class stack { private : T *dataptr; int top; int capacity; public: stack(int cap=100); int getCapacity() {return capacity;} void push(T b); T pop() {assert(top>0); return dataptr[--top];} bool isEmpty() {return top==0;} }; Stack as a Class Template
  • 21. 21 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; } }
  • 22. 22 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> intS(5); // a stack of integers cout<<"intS capacity after construction = "<<intS.getCapacity()<<endl; int x[]={2,3,7,8,-10,14,5}; for (int i=0;i<7;i++) intS.push(x[i]); cout<<"intS capacity after pushing 7 elements="<< intS.getCapacity(); cout<<“nEmptying intS: "; while (!intS.isEmpty()) cout<<intS.pop()<<"; "; cout<<endl;
  • 23. 23 stack<char *> stringS(5); // a stack of strings stringS.push("hi"); stringS.push("there"); cout<<"Emptying stringS: "; while (!stringS.isEmpty()) cout<<stringS.pop()<<"; "; cout<<endl; double y[]={3.14,9.8,1.42,12}; stack<double> doubleS(y,4); // a stack of doubles cout<<"doubleS capacity="<<doubleS.getCapacity()<<endl; cout<<"Emptying doubleS: "; while (!doubleS.isEmpty()) cout<<doubleS.pop()<<"; "; cout<<endl; }
  • 24. 24 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>
  • 25. 25 Some Operations of STL Classes stack queue // 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 // 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