SlideShare a Scribd company logo
1
C++: Object-Oriented
Programming
• Classes and Objects
• Template classes
• Operator Overloading
• Inheritance
• Polymorphism
2
The Evolution of The Notion of
Object
• In C, a struct models what a thing has/is (i.e., the
data, also called the characteristics), but not what
it does (its behavior, represented by functions).
• The functions are outside and separate from
structs.
• In C++, the characteristics and behavior are
integrated into a single structure, called object.
• The data type of an object is the class of the object
• The packaging of the data and the functions into a
class type is called data encapsulation.
3
Example: A Basic Stack
(Using C structs)
struct stack {
int data[100];
int top;
} S;
int isEmpty(stack S){
return S.top==0?1:0;
}
int pop(stack S){
assert(top>0);
return S.data[--S.top];
}
void push(stack S, int a){
assert(top<100);
S.data[top]=a; S.top++;
}
4
Problems with structs
• Need a different struct for each different
data type to be pushed onto or popped off
the stack
• Overflow (although it can be fixed in C,
using dynamic data allocation)
• The overall structure does not convey a
tight coupling between the stack data and
the stack operations
5
How struct Becomes in C++
(1st
step: put the functions inside )
struct stack {
int data[100];
int top;
void push(int a); // implement outside
int pop(void); // implement outside
bool isEmpty(void); // implement outside
} ;
6
2nd
Step: Implement the Functions
void stack::push(int a){
assert(top<100);
data[top]=a;
top++;
}
bool stack::isEmpty( ){
return top==0?true:false;
}
int stack:: pop( ){
assert(top>0);
int x=data[--top];
return x;
}
7
How to Use the New Data Type
Statements Outcome
stack S; S.top=0;
S.push(12); S.push(20);
S.push(30);
int x=S.pop();
cout<<x<<endl;
cout<S.pop()<<endl;
cout<S.isEmpty()<<endl;
cout<S.pop()<<endl;
cout<S. isEmpty()<<endl
30
20
false
12
true
8
Definition of Classes and
Objects (revisited)
• A new data type defined with struct (where the
data and functions are together) is called a class.
– Example: the data type stack is a class
• Indeed, C++ has a new reserved word, class, that
is synonymous to struct (except for a minor
difference explained later)
• Any variable of the type defined by struct or class
is called an object or instance of that class
– Example: In the declaration: stack S;, S is an object of
the stack class.
9
Definition of Members
• The declared variables inside structs are
called the data fields in C.
• In C++, the declared variables and functions
inside structs/classes are called members:
– member variables
– member functions (also called methods)
10
Data Hiding: Context
• Note that users of a stack object can access
directly the members data[] and top
• For example, a user can do:
• But notice that the 3 stack operations are all the
users need. They do need to access top directly
• Also, this free access can cause problems:
– If a user is not careful or is malicious, such a direct
access to S.top can invalidate the stack operations’
outcome
– It also limits the implementer from evolving/modifying
the implementation of the data type
S.top -= 3;
11
Data Hiding: Private and
Public sections
• C++, and other object-oriented programming
languages, allow the programmer to designate
certain members of a class as private, and other
members as public.
• Private members cannot be accessed from outside
the class, while public members can
• Private members are hidden (thus the term data
hiding)
12
The Stack with Data Hiding
struct stack { // or class stack {
private :
int data[100];
int top;
public:
void push(int a);
int pop(void);
bool isEmpty(void);
} ;
Now, observe which
access is legal and
which is illegal (will
not compile):
stack S;
S.top = 10; //illegal
S.data[17]=22; // illegal
S.push(5); //legal
S.isEmpty(); //legal
S.pop(); // legal
13
Initialization of Variables
• In C, initialization of variables is left to the user.
• For example, the member “top” of stack S is not
initialized. All calls to push() or pop() cause errors
• C++ considers initialization too important to leave
to the users’ unreliable memory to remember to
initialize.
• Even if users remember, observe that:
– In the definition of stack, it is illegal to write: int
top=0;
– If top is private, it is illegal to write: stack S; S.top = 0;
– And we don’t want to have top public (as we saw)
14
Initialization and Constructors
• C++ requires that every class have a constructor
• The constructor is responsible for initializing
objects automatically whenever they are declared.
• The programmer has the option to provide his/her
own constructors, which get called whenever a
new object is declared
• Otherwise, the compiler provides a default
constructor
• But what is a constructor?
15
Constructors (Contd.)
• The constructor is like any other method (i.e.,
member function) in that
– it takes arguments
– it can be overloaded
– its arguments can be defaulted
• But with one big difference: It has no return value,
not even void.
• One other very important characteristic: the
constructor’s name is the same as the class name
16
Constructor of the Stack Class
class stack {
private :
int data[100];
int top;
public:
stack(); // the constructor
void push(int a);
…// the other functions
} ;
// constructor: initializes
// top to 0.
stack::stack(){
top=0;
}
// the implementation of
// the other functions is
// the same as before
17
How to Create Objects Using
Constructors
• Example: stack S();
• This creates S as a stack, and initializes its
member “top” to 0.
• Now, we can start to call S.push(int),
S.pop(), and S.isEmpty() without problems.
18
Constructors with Arguments
& Constructor Overloading
• Suppose that when you create a stack, you
want to “stuff” it with several specified
values at the outset
• This can be done by writing a constructor
that take the specified values as input, and
initializes the data[ ] to those values.
• This is shown next.
19
class stack {
private :
int data[100];
int top;
public:
stack();
stack(int a[], int n);
//other functions
};
//constructor: initializes data to a
stack::stack(int a[],int n){
for(top=0;top<n && top<100;
top++)
data[top]=a[top];
}
// constructor: initializes top to 0.
stack::stack(){
top=0;
}
20
Stack Overflow and Solution
• So far, the stack example we have cannot
hold more than 100 values. If we push more
than that many, the stack overflows.
• To overcome this limit, we can use dynamic
arrays (with new), and maintain a capacity
indicator
• This is implemented next
21
class stack {
private :
int *dataptr;
int top;
int capacity;
public:
stack(int cap=100);
stack(int a[], int n);
int getCapacity() {
return capacity;}
void push(int b);
int pop();
bool isEmpty() {
return top==0;}
};
//constructor: sets capacity to
// max(2n,100); stores a[] in stack
stack::stack(int a[],int n){
capacity = (2*n>100)?2*n:100;
dataptr = new int[capacity];
for(top=0;top<n;top++)
dataptr[top]=a[top];
}
// constructor: initializes top to 0,
// and capacity to cap if provided
// & >0, otherwise to 100.
stack::stack(int cap){
top=0;
capacity = (cap>0)?cap:100;
dataptr = new int[capacity];
}
22
void stack::push(int b){
if (top < capacity)
dataptr[top++]=b;
else{
// double the capacity, copy
// current contents to new array,
// delete old array, and push b on
// top of the new array
capacity *=2;
int *newptr=new int [capacity];
for(int k=0;k<capacity/2;k++)
newptr[k]=dataptr[k];
delete [] dataptr;
dataptr = newptr;
dataptr[top++]=b;
}
}
Inline Functions:
Note that the
methods isEmpty()
and getCapacity()
are implemented
inside the class.
Such functions are
called inline
functions. Inline
functions should
be limited to very
simple
implementations.
23
One Last Elaboration on the Stack
Class: Generic Data Type
• The stack class allows us to push integers only
• Clearly, one may need a stack for floats or doubles
or chars or even user-defined types
• Sure, one can design a different stack class for
each different data type (cut and paste, and change
the data type)
• But that is cumbersome, error-prone, and
inefficient when it comes to making changes
• A better alternative: class templates
24
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
25
Class Templates Syntax
• For template class 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){……}
26
template <class T> class stack {
private :
T *dataptr;
int top;
int capacity;
public:
stack(int cap=100); // as before
stack(T a[], int n); // new
int getCapacity() {return capacity;}
void push(T b);
T pop() {assert(top>0); return dataptr[--top];}
bool isEmpty() {return top==0;}
};
Stack as a Template Class
27
//constructor: sets capacity to max(2n,100).
// It then initializes stack to a[].
template<class T> stack<T>::stack(T a[],int n){
capacity = (2*n>100)?2*n:100;
dataptr = new T[capacity];
for(top=0;top<n;top++)
dataptr[top]=a[top];
}
// constructor: initializes top to 0, and capacity to cap
// if provided & >0, otherwise to 100.
template<class T> stack<T>::stack(int cap){
top=0;
capacity = (cap>0)?cap:100;
dataptr = new T[capacity];
}
28
template<class T> void stack<T>::push(T b){
if (top < capacity)
dataptr[top++]=b;
else{
// double the capacity, copy
// current contents to new array,
// delete old array, and push b on
// top of the new array
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;
}
}
29
A Complete Program Using Template Stacks
#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;
30
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;
}
31
The Output of the Last Program
intS capacity after construction = 5
intS capacity after pushing 7 elements=10
Emptying intS: 5; 14; -10; 8; 7; 3; 2;
Emptying stringS: there; hi;
doubleS capacity=100
Emptying doubleS: 12; 1.42; 9.8; 3.14;

More Related Content

What's hot

Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
Vineeta Garg
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
Jay Patel
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
Hermann Hueck
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
Selvin Josy Bai Somu
 
Multiple file programs, inheritance, templates
Multiple file programs, inheritance, templatesMultiple file programs, inheritance, templates
Multiple file programs, inheritance, templates
Syed Zaid Irshad
 
Refactoring - improving the smell of your code
Refactoring - improving the smell of your codeRefactoring - improving the smell of your code
Refactoring - improving the smell of your code
vmandrychenko
 
Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
Lovely Professional University
 
Basics of objective c
Basics of objective cBasics of objective c
Basics of objective c
sagaroceanic11
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
mohamedsamyali
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
mohamedsamyali
 
147301 nol
147301 nol147301 nol
147301 nol
Jeyakrishnan V
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
Haresh Jaiswal
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Gandhi Ravi
 
Visula C# Programming Lecture 7
Visula C# Programming Lecture 7Visula C# Programming Lecture 7
Visula C# Programming Lecture 7
Abou Bakr Ashraf
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
HelpWithAssignment.com
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
Ali Aminian
 
Tutconstructordes
TutconstructordesTutconstructordes
Tutconstructordes
Niti Arora
 
C++ 11
C++ 11C++ 11

What's hot (19)

Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
 
Multiple file programs, inheritance, templates
Multiple file programs, inheritance, templatesMultiple file programs, inheritance, templates
Multiple file programs, inheritance, templates
 
Refactoring - improving the smell of your code
Refactoring - improving the smell of your codeRefactoring - improving the smell of your code
Refactoring - improving the smell of your code
 
Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
 
Basics of objective c
Basics of objective cBasics of objective c
Basics of objective c
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
147301 nol
147301 nol147301 nol
147301 nol
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Visula C# Programming Lecture 7
Visula C# Programming Lecture 7Visula C# Programming Lecture 7
Visula C# Programming Lecture 7
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
 
Tutconstructordes
TutconstructordesTutconstructordes
Tutconstructordes
 
C++ 11
C++ 11C++ 11
C++ 11
 

Viewers also liked

C++ classes
C++ classesC++ classes
C++ classes
imhammadali
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Classes and objects till 16 aug
Classes and objects till 16 augClasses and objects till 16 aug
Classes and objects till 16 aug
shashank12march
 
[KOSSA] C++ Programming - 14th Study - template
[KOSSA] C++ Programming - 14th Study - template[KOSSA] C++ Programming - 14th Study - template
[KOSSA] C++ Programming - 14th Study - template
Seok-joon Yun
 
Array,lists and hashes in perl
Array,lists and hashes in perlArray,lists and hashes in perl
Array,lists and hashes in perl
sana mateen
 
Lists, queues and stacks
Lists, queues and stacksLists, queues and stacks
Lists, queues and stacks
andreeamolnar
 
098ca session7 c++
098ca session7 c++098ca session7 c++
098ca session7 c++
Mukund Trivedi
 
C++ Language
C++ LanguageC++ Language
C++ Language
Vidyacenter
 
Intro To C++ - Class 14 - Midterm Review
Intro To C++ - Class 14 - Midterm ReviewIntro To C++ - Class 14 - Midterm Review
Intro To C++ - Class 14 - Midterm Review
Blue Elephant Consulting
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
rohassanie
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
nirajmandaliya
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
Princess Sam
 
Template at c++
Template at c++Template at c++
Template at c++
Lusain Kim
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
UniSoftCorner Pvt Ltd India.
 
C++ Template
C++ TemplateC++ Template
C++ Template
Saket Pathak
 
class c++
class c++class c++
class c++
vinay chauhan
 
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. PatilDiscrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
widespreadpromotion
 
Set Theory In C++
Set Theory In C++Set Theory In C++
Set Theory In C++
Yan (Andrew) Zhuang
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
Vivek chan
 

Viewers also liked (20)

C++ classes
C++ classesC++ classes
C++ classes
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Classes and objects till 16 aug
Classes and objects till 16 augClasses and objects till 16 aug
Classes and objects till 16 aug
 
[KOSSA] C++ Programming - 14th Study - template
[KOSSA] C++ Programming - 14th Study - template[KOSSA] C++ Programming - 14th Study - template
[KOSSA] C++ Programming - 14th Study - template
 
Array,lists and hashes in perl
Array,lists and hashes in perlArray,lists and hashes in perl
Array,lists and hashes in perl
 
Lists, queues and stacks
Lists, queues and stacksLists, queues and stacks
Lists, queues and stacks
 
098ca session7 c++
098ca session7 c++098ca session7 c++
098ca session7 c++
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Intro To C++ - Class 14 - Midterm Review
Intro To C++ - Class 14 - Midterm ReviewIntro To C++ - Class 14 - Midterm Review
Intro To C++ - Class 14 - Midterm Review
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
 
Template at c++
Template at c++Template at c++
Template at c++
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
 
C++ Template
C++ TemplateC++ Template
C++ Template
 
class c++
class c++class c++
class c++
 
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
 
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. PatilDiscrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
 
Set Theory In C++
Set Theory In C++Set Theory In C++
Set Theory In C++
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
 

Similar to OOP

Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
rehan16091997
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
ssuser0c24d5
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
nilesh405711
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
YashpalYadav46
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
DevliNeeraj
 
Templates2
Templates2Templates2
Templates2
zindadili
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
c++ ppt.ppt
c++ ppt.pptc++ ppt.ppt
c++ ppt.ppt
FarazKhan89093
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
Dhaval Kaneria
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
Michael Heron
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
MZGINBarwary
 
c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
Classes and objects
Classes and objectsClasses and objects
Classes and objects
Shailendra Veeru
 
9781285852744 ppt ch18
9781285852744 ppt ch189781285852744 ppt ch18
9781285852744 ppt ch18
Terry Yoast
 
CS1Lesson13-IntroClasses.pptx
CS1Lesson13-IntroClasses.pptxCS1Lesson13-IntroClasses.pptx
CS1Lesson13-IntroClasses.pptx
ChetanChauhan203001
 
Python-for-Data-Analysis.pdf
Python-for-Data-Analysis.pdfPython-for-Data-Analysis.pdf
Python-for-Data-Analysis.pdf
ssuser598883
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
Steve Johnson
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
Connex
 
04cpp inh
04cpp inh04cpp inh
04cpp inh
Jihin Raju
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
Ananthu Mahesh
 

Similar to OOP (20)

Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
Templates2
Templates2Templates2
Templates2
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
c++ ppt.ppt
c++ ppt.pptc++ ppt.ppt
c++ ppt.ppt
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
c++ Unit I.pptx
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
9781285852744 ppt ch18
9781285852744 ppt ch189781285852744 ppt ch18
9781285852744 ppt ch18
 
CS1Lesson13-IntroClasses.pptx
CS1Lesson13-IntroClasses.pptxCS1Lesson13-IntroClasses.pptx
CS1Lesson13-IntroClasses.pptx
 
Python-for-Data-Analysis.pdf
Python-for-Data-Analysis.pdfPython-for-Data-Analysis.pdf
Python-for-Data-Analysis.pdf
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
04cpp inh
04cpp inh04cpp inh
04cpp inh
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 

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

官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
shadow0702a
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
ecqow
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...
IJECEIAES
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
bjmsejournal
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
LAXMAREDDY22
 
Seminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptxSeminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptx
Madan Karki
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
gowrishankartb2005
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
GauravCar
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
Nada Hikmah
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
UReason
 

Recently uploaded (20)

官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
 
Seminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptxSeminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptx
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
 

OOP

  • 1. 1 C++: Object-Oriented Programming • Classes and Objects • Template classes • Operator Overloading • Inheritance • Polymorphism
  • 2. 2 The Evolution of The Notion of Object • In C, a struct models what a thing has/is (i.e., the data, also called the characteristics), but not what it does (its behavior, represented by functions). • The functions are outside and separate from structs. • In C++, the characteristics and behavior are integrated into a single structure, called object. • The data type of an object is the class of the object • The packaging of the data and the functions into a class type is called data encapsulation.
  • 3. 3 Example: A Basic Stack (Using C structs) struct stack { int data[100]; int top; } S; int isEmpty(stack S){ return S.top==0?1:0; } int pop(stack S){ assert(top>0); return S.data[--S.top]; } void push(stack S, int a){ assert(top<100); S.data[top]=a; S.top++; }
  • 4. 4 Problems with structs • Need a different struct for each different data type to be pushed onto or popped off the stack • Overflow (although it can be fixed in C, using dynamic data allocation) • The overall structure does not convey a tight coupling between the stack data and the stack operations
  • 5. 5 How struct Becomes in C++ (1st step: put the functions inside ) struct stack { int data[100]; int top; void push(int a); // implement outside int pop(void); // implement outside bool isEmpty(void); // implement outside } ;
  • 6. 6 2nd Step: Implement the Functions void stack::push(int a){ assert(top<100); data[top]=a; top++; } bool stack::isEmpty( ){ return top==0?true:false; } int stack:: pop( ){ assert(top>0); int x=data[--top]; return x; }
  • 7. 7 How to Use the New Data Type Statements Outcome stack S; S.top=0; S.push(12); S.push(20); S.push(30); int x=S.pop(); cout<<x<<endl; cout<S.pop()<<endl; cout<S.isEmpty()<<endl; cout<S.pop()<<endl; cout<S. isEmpty()<<endl 30 20 false 12 true
  • 8. 8 Definition of Classes and Objects (revisited) • A new data type defined with struct (where the data and functions are together) is called a class. – Example: the data type stack is a class • Indeed, C++ has a new reserved word, class, that is synonymous to struct (except for a minor difference explained later) • Any variable of the type defined by struct or class is called an object or instance of that class – Example: In the declaration: stack S;, S is an object of the stack class.
  • 9. 9 Definition of Members • The declared variables inside structs are called the data fields in C. • In C++, the declared variables and functions inside structs/classes are called members: – member variables – member functions (also called methods)
  • 10. 10 Data Hiding: Context • Note that users of a stack object can access directly the members data[] and top • For example, a user can do: • But notice that the 3 stack operations are all the users need. They do need to access top directly • Also, this free access can cause problems: – If a user is not careful or is malicious, such a direct access to S.top can invalidate the stack operations’ outcome – It also limits the implementer from evolving/modifying the implementation of the data type S.top -= 3;
  • 11. 11 Data Hiding: Private and Public sections • C++, and other object-oriented programming languages, allow the programmer to designate certain members of a class as private, and other members as public. • Private members cannot be accessed from outside the class, while public members can • Private members are hidden (thus the term data hiding)
  • 12. 12 The Stack with Data Hiding struct stack { // or class stack { private : int data[100]; int top; public: void push(int a); int pop(void); bool isEmpty(void); } ; Now, observe which access is legal and which is illegal (will not compile): stack S; S.top = 10; //illegal S.data[17]=22; // illegal S.push(5); //legal S.isEmpty(); //legal S.pop(); // legal
  • 13. 13 Initialization of Variables • In C, initialization of variables is left to the user. • For example, the member “top” of stack S is not initialized. All calls to push() or pop() cause errors • C++ considers initialization too important to leave to the users’ unreliable memory to remember to initialize. • Even if users remember, observe that: – In the definition of stack, it is illegal to write: int top=0; – If top is private, it is illegal to write: stack S; S.top = 0; – And we don’t want to have top public (as we saw)
  • 14. 14 Initialization and Constructors • C++ requires that every class have a constructor • The constructor is responsible for initializing objects automatically whenever they are declared. • The programmer has the option to provide his/her own constructors, which get called whenever a new object is declared • Otherwise, the compiler provides a default constructor • But what is a constructor?
  • 15. 15 Constructors (Contd.) • The constructor is like any other method (i.e., member function) in that – it takes arguments – it can be overloaded – its arguments can be defaulted • But with one big difference: It has no return value, not even void. • One other very important characteristic: the constructor’s name is the same as the class name
  • 16. 16 Constructor of the Stack Class class stack { private : int data[100]; int top; public: stack(); // the constructor void push(int a); …// the other functions } ; // constructor: initializes // top to 0. stack::stack(){ top=0; } // the implementation of // the other functions is // the same as before
  • 17. 17 How to Create Objects Using Constructors • Example: stack S(); • This creates S as a stack, and initializes its member “top” to 0. • Now, we can start to call S.push(int), S.pop(), and S.isEmpty() without problems.
  • 18. 18 Constructors with Arguments & Constructor Overloading • Suppose that when you create a stack, you want to “stuff” it with several specified values at the outset • This can be done by writing a constructor that take the specified values as input, and initializes the data[ ] to those values. • This is shown next.
  • 19. 19 class stack { private : int data[100]; int top; public: stack(); stack(int a[], int n); //other functions }; //constructor: initializes data to a stack::stack(int a[],int n){ for(top=0;top<n && top<100; top++) data[top]=a[top]; } // constructor: initializes top to 0. stack::stack(){ top=0; }
  • 20. 20 Stack Overflow and Solution • So far, the stack example we have cannot hold more than 100 values. If we push more than that many, the stack overflows. • To overcome this limit, we can use dynamic arrays (with new), and maintain a capacity indicator • This is implemented next
  • 21. 21 class stack { private : int *dataptr; int top; int capacity; public: stack(int cap=100); stack(int a[], int n); int getCapacity() { return capacity;} void push(int b); int pop(); bool isEmpty() { return top==0;} }; //constructor: sets capacity to // max(2n,100); stores a[] in stack stack::stack(int a[],int n){ capacity = (2*n>100)?2*n:100; dataptr = new int[capacity]; for(top=0;top<n;top++) dataptr[top]=a[top]; } // constructor: initializes top to 0, // and capacity to cap if provided // & >0, otherwise to 100. stack::stack(int cap){ top=0; capacity = (cap>0)?cap:100; dataptr = new int[capacity]; }
  • 22. 22 void stack::push(int b){ if (top < capacity) dataptr[top++]=b; else{ // double the capacity, copy // current contents to new array, // delete old array, and push b on // top of the new array capacity *=2; int *newptr=new int [capacity]; for(int k=0;k<capacity/2;k++) newptr[k]=dataptr[k]; delete [] dataptr; dataptr = newptr; dataptr[top++]=b; } } Inline Functions: Note that the methods isEmpty() and getCapacity() are implemented inside the class. Such functions are called inline functions. Inline functions should be limited to very simple implementations.
  • 23. 23 One Last Elaboration on the Stack Class: Generic Data Type • The stack class allows us to push integers only • Clearly, one may need a stack for floats or doubles or chars or even user-defined types • Sure, one can design a different stack class for each different data type (cut and paste, and change the data type) • But that is cumbersome, error-prone, and inefficient when it comes to making changes • A better alternative: class templates
  • 24. 24 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
  • 25. 25 Class Templates Syntax • For template class 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){……}
  • 26. 26 template <class T> class stack { private : T *dataptr; int top; int capacity; public: stack(int cap=100); // as before stack(T a[], int n); // new int getCapacity() {return capacity;} void push(T b); T pop() {assert(top>0); return dataptr[--top];} bool isEmpty() {return top==0;} }; Stack as a Template Class
  • 27. 27 //constructor: sets capacity to max(2n,100). // It then initializes stack to a[]. template<class T> stack<T>::stack(T a[],int n){ capacity = (2*n>100)?2*n:100; dataptr = new T[capacity]; for(top=0;top<n;top++) dataptr[top]=a[top]; } // constructor: initializes top to 0, and capacity to cap // if provided & >0, otherwise to 100. template<class T> stack<T>::stack(int cap){ top=0; capacity = (cap>0)?cap:100; dataptr = new T[capacity]; }
  • 28. 28 template<class T> void stack<T>::push(T b){ if (top < capacity) dataptr[top++]=b; else{ // double the capacity, copy // current contents to new array, // delete old array, and push b on // top of the new array 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; } }
  • 29. 29 A Complete Program Using Template Stacks #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;
  • 30. 30 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; }
  • 31. 31 The Output of the Last Program intS capacity after construction = 5 intS capacity after pushing 7 elements=10 Emptying intS: 5; 14; -10; 8; 7; 3; 2; Emptying stringS: there; hi; doubleS capacity=100 Emptying doubleS: 12; 1.42; 9.8; 3.14;