CS 1031 C++: Object-Oriented Programming Classes and Objects Template classes Operator Overloading Inheritance Polymorphism.

Slides:



Advertisements
Similar presentations
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Advertisements

Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
Dynamic Allocation Eric Roberts CS 106B February 4, 2013.
1 Stacks Chapter 4. 2 Objectives You will be able to: Describe a stack as an ADT. Build a dynamic-array-based implementation of stacks. Build a linked-list.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
1 Lecture 24 Abstract Data Types (ADT) –I Overview  What is an Abstract Data type?  What is Stack ADT?  Stack ADT Specifications  Array Implementation.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 22 - C++ Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Abstract data types & object-oriented paradigm. Abstraction Abstraction: a view of an entity that includes only the attributes of significance in a particular.
Stacks  Standard operations: IsEmpty … return true iff stack is empty Top … return top element of stack Push … add an element to the top of the stack.
Lecture 9 Concepts of Programming Languages
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
1 Review: Two Programming Paradigms Structural (Procedural) Object-Oriented PROGRAM PROGRAM FUNCTION OBJECT Operations Data OBJECT Operations Data OBJECT.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Operator Overloading in C++
Review of C++ Programming Part II Sheng-Fang Huang.
Object Oriented Data Structures
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Templates Zhen Jiang West Chester University
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Chapter 3 Introduction to Collections – Stacks Modified
CS 1031 The C++ Language C Evolves into C++ Object Oriented Programming –Classes and Objects –Operator Overloading –Inheritance –Polymorphism –Template.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Stack and Heap Memory Stack resident variables include:
Structured Programming Instructor: Prof. K. T. Tsang Lecture 13:Object 物件 Oriented 面向 Programming (OOP)
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
CS 1031 Final Touches: Multiple-File Programs, Inheritance, Templates Multiple-File Programs –header files –implementation files –main-program file) Inheritance.
Chapter 10 Introduction to Classes
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
CS240 Computer Science II Function and Class Templates (Based on Deitel) Dr. Erh-Wen Hu.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
(1) ICS 313: Programming Language Theory Chapter 11: Abstract Data Types (Data Abstraction)
TEMPLATESTEMPLATES BCAS,Bapatla B.mohini devi. Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type Parameters 22.4Templates.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
1 Classes classes and objects - from object-oriented programming point of view class declaration class class_name{ data members … methods (member functions)
1 Introduction to Object Oriented Programming Chapter 10.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
 2000 Deitel & Associates, Inc. All rights reserved. 12.1Introduction Templates - easily create a large range of related functions or classes –function.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Introduction of Object Oriented Programming.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
C vs C++. Oops Advantages simplicity: software objects model real world objects, so the complexity is reduced and the program structure is very clear;
C++: Object-Oriented Programming
Introduction to Custom Templates
Review: Two Programming Paradigms
Stacks.
Introduction to Classes
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
CONSTRUCTORS AND DESRUCTORS
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Class and Objects In a class, all the functions that operate on the data structure are grouped together in one place along with the data Like a struct.
C++: Object-Oriented Programming
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Presentation transcript:

CS 1031 C++: Object-Oriented Programming Classes and Objects Template classes Operator Overloading Inheritance Polymorphism

CS 1032 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.

CS 1033 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++; }

CS 1034 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

CS 1035 How struct Becomes in C++ (1 st 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 } ;

CS nd 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; }

CS 1037 How to Use the New Data Type StatementsOutcome 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 false 12 true

CS 1038 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.

CS 1039 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)

CS 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;

CS 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)

CS 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

CS 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)

CS 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?

CS 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

CS 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

CS 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.

CS 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.

CS 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; }

CS 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

CS 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]; }

CS 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.

CS 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

CS 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 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_declaration; template return_type className ::methodName(parameter-list){ ……} template className :: className(parameter-list){……}

CS template 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

CS //constructor: sets capacity to max(2n,100). // It then initializes stack to a[]. template stack ::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 stack ::stack(int cap){ top=0; capacity = (cap>0)?cap:100; dataptr = new T[capacity]; }

CS template void stack ::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; }

CS A Complete Program Using Template Stacks #include using namespace std; // template stack definition goes here int main(int argc, char *argv[]){ stack 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;

CS stack 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 doubleS(y,4); // a stack of doubles cout<<"doubleS capacity="<<doubleS.getCapacity()<<endl; cout<<"Emptying doubleS: "; while (!doubleS.isEmpty()) cout<<doubleS.pop()<<"; "; cout<<endl; }

CS 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;