SlideShare a Scribd company logo
DATA ABSTRACTION: USER DEFINED TYPES AND THE CLASS
DATA TYPES A  DATA TYPE  IS A FORMAL DESCRIPTION OF: 1. THE DOMAIN THAT AN OBJECT OF THAT TYPE CAN HAVE. 2. THE BASIC SET OF OPERATIONS THAT CAN BE APPLIED TO VALUES OF THAT TYPE. 3. DATA REPRESENTATION.
THE FORMAL DESCRIPTION OF  int  AND  float  VALUES AND THE ALLOWABLE OPERATIONS ON SUCH DATA TYPE COME FROM MATHEMATICS. THE OPERATIONS ARE:  + ,  - ,   * ,  AND   / .  THE RANGE OF VALUES CAN BE LISTED AS  INT_MIN  TO  INT_MAX .
THE VALUES OF TYPE  char  ARE THE ALPHANUMERIC CHARACTERS OF  THE  ASCII  SET. MEMBERS ARE ORDERED IN RELATION TO EACH OTHER. '0' < '1' < '2' <  ... '7' < '8' < '9' AND 'a' < 'b' < 'c'< ... 'x' < 'y' < 'z'
AN OBJECT OF THE  BASIC TYPES  int ,  float ,  AND   char   CAN HOLD ONLY ONE VALUE.  EACH ONE IS MADE UP OF INDIVISIBLE, OR ATOMIC ELEMENTS. int  AND  char   SHARE A COMMON PROPERTY: THEY ARE ORDINAL TYPES.  THE VALUES OF EACH TYPE CAN BE LISTED IN A SEQUENCE.
IN SOME INSTANCES, THE BASIC TYPES MAY NOT BE SUITABLE FOR DATA REPRESENTATION, OR SIMPLY NOT QUITE READABLE.  C++ HAS A MECHANISM FOR ALLOWING TO CREATE NEW DATA TYPES.  THAT IS, THE PROGRAMMERS DECLARE AND DEFINE NEW TYPES.  DATA ABSTRACTION: SIMPLE TYPES (USER-DEFINED)
EXAMPLE: TYPE DEFINITION  typedef   existing_type_name new_type_name ;
A  SIMULATION  OF THE TYPE  Logical : typedef int   Logical; const Logical TRUE = 1; const Logical FALSE = 0; : Logical positive;  :  positive = TRUE;  // initialize flag
MORE ON DATA ABSTRACTION ABSTRACT DATA TYPES PROVIDE FOR THE ABILITY TO MODEL THE DOMAIN AND OPERATIONS OF DATA WITHOUT ANY CONCERN ABOUT IMPLEMENTATION.
THE CASE OF THE &quot;COUNTER&quot; A COUNTER IS A SIMPLE INTEGER VARIABLE. ITS VALUE IS CHANGED AND ACCESSED DEPENDING ON SOME OTHER TASK.
COMMON OPERATIONS PERFORMED  (ON THE INTEGER VARIABLE)  ARE: 1. CLEAR (START AT SOME INITIAL VALUE) 2. ALTER THE VALUE TO KEEP TRACK OF TASK (INCREMENT) 3. ALTER THE VALUE TO KEEP TRACK OF TASK (DECREMENT) 4. EXAMINE OR PRINT THE CURRENT VALUE (ACCESS)
EXAMPLE: PROBLEM : GRADUATION CERTIFICATION REFERS TO EVALUATING EARNED CREDITS TO ASSURE THAT STUDENTS HAVE SATISFIED CURRICULUM REQUIREMENTS.  SOME STUDENTS DO, SOME DO NOT.  DEVELOP AND IMPLEMENT A SYSTEM THAT KEEPS TRACK OF THOSE STUDENTS WHO ARE GRADUATING AND THOSE THAT ARE DELAYED BASED ON NUMBER OF CREDITS EARNED.
ANALYSIS : 1. DISCUSSION  (ONLY REGARDING COUNTER) THE OPERATIONS TO BE PERFORMED ON THE  COUNTER   ARE:  INITIALIZE INCREMENT DECREMENT ACCESS
2. SPECIFICATION  (ONLY REGARDING COUNTER) a)  OPERATIONS void Initialize(int); void Increment(); void Decrement(); int Access_Value(); b)  DATA int value;
GRAD-VALID VALIDATE GET_CREDITS  PRINT RESULT LEVEL 0 LEVEL 1 3. STRUCTURE CHART
NEW CONCEPTS THE CLASS
RELATIONSHIP BETWEEN DATA AND OPERATIONS: SEPARATE ENTITIES PROCESS A DATA STRUCTURES CONTROL STRUCTURES PROCESS D PROCESS C PROCESS B
ALTERNATIVE REPRESENTATION THE  CLASS  , A SET OF OBJECTS, ALLOWS FOR THE REPRESENTATION OF DATA AND OPERATIONS INTO A COHESIVE UNIT.
RELATIONSHIP BETWEEN DATA AND OPERATIONS: A COHERENT UNIT CONTROL STRUCTURES AND DATA STRUCTURES PROCESS A PROCESS D PROCESS C PROCESS B DATA
THE C++ CLASS A MECHANISM TO MODEL OBJECTS WITH MULTIPLE ATTRIBUTES. THE C++ CLASS ALLOWS FOR THE DEFINITION A NEW TYPE OF DATA ACCORDING TO THE NEEDS OF THE PROBLEM, AND TO DEFINE OPERATIONS (METHODS) TO ACT UPON THE TYPE (ABSTRACT DATA TYPING).
INFORMATION HIDING THE ENCAPSULATION OF IMPLEMENTATION DETAILS.  PRIVATE CODE AND DATA CANNOT BE ACCESSED DIRECTLY.
CLASS SYNTAX class  <class_name> { public: <public declaration list> private: <private declaration list> };
class  <class_name> { public: <public data structures> // optional <constructors> // optional <function prototypes> // optional private: // optional <private data structures> // optional <function prototypes> // optional };
EXAMPLE 1 // class declaration section class Date { private: int month; //a data member int day;  // a data member int year;  // a data member public: Date( int = 11, int = 16, int = 2001  ); // the constructor void setdate(int, int, int); // a member function void showdate();  // a member function } ;
SYNTAX OF DEFINING  MEMBER FUNCTIONS <return_type>  <class_name> :: <function_name>     ( <parameter_list> ) { <function member body> }
EXAMPLE 1 // class implementation section Date::Date( int mm, int dd, int yyyy) { month = mm; day  = dd; year = yyyy; } void Date:: setdate(int mm, int dd, int yyyy) { month = mm; day  = dd; year = yyyy; return ; }
void Date::showdate() { cout<< “ The date is  “; cout<< setfill ( ‘0’) << setw(2)<< month << ‘/ ‘ << setw(2)<< day << ‘/ ‘ << setw(2)<< year % 100 ; // extract last  //two year digits cout<< ednl ; return ; }
Class Scope and Accessing Class Members A class data members and function members belong to that class scope. Nonmember functions are defined as file scope. Within class scope members are accessible by using their name Outside class scope, class members are referenced through one of the handles on an object – an object name, a reference to an object or pointer to an object. Variable defined in member function has function scope. You can hide data member in a function by using same name.
Once the class has been defined, it can be used as a type in object, array and pointer definitions. For example class Date can be used in the following main function as follows
int main () { Date a, b, c(4, 1, 1998) // declare three objects –    //initialize one of them b.setdate(12, 25, 2002);//assign values to b’s data members a.Showdate( ); // display object a’s values b.Showdate( ); // display object b’s values c.Showdate( ); // display object c’s values return 0 ; } /*output The date is 07/04/01   The date is 12/25/02   The date is 04/01/98 */
IMPLEMENTATION: THE  Counter  CLASS // File: Counter.h #include <limits.h> // contains definitions of // INT_MAX and INT_MIN class Counter { public:  // member functions void Initialize(int init_value); // initialize counter void Increment(); // increment counter void Decrement(); // decrement counter int Access_Value(); // return current counter // value private:   // data members int value; };
void Counter::Initialize(int init_value) // initialize counter { value = init_value; } // Initialize() void Counter::Increment()  // increment counter { if (value < INT_MAX) value++; else cerr << &quot;Counter overflow. Increment ignored.&quot; << endl; } // Increment()
void Counter::Decrement()  // decrement counter { if (value > INT_MIN) value--; else cerr << &quot;Counter underflow. Decrement ignored.&quot; << endl; } // Decrement() int Counter::Access_Value() // return current counter value { return value; } // Access_Value()
#include <iostream.h> #include &quot;Counter.h&quot; void main() {  // Minimum credits for graduation const int GRAD_LEVEL = 130; // local objects of class Counter Counter c_graduated; Counter c_delayed; // local data int class_size, number_of_credits; int i; // get the graduating class size cout << &quot;Enter the class size: &quot;; cin >> class_size; IMPLEMENTATION (USING THE  Counter  CLASS)
// initialize counter values c_graduated.Initialize(0); c_delayed.Initialize(class_size); // use of Increment() and Decrement() for (i = 0; i < class_size; i++) {  cout << &quot;Please enter the number of validated credits: &quot;; cin >> number_of_credits; if (number_of_credits >= GRAD_LEVEL) { c_graduated.Increment(); c_delayed.Decrement(); } }  // print results using Access_value() cout << &quot;The number of students graduating this semester: &quot;  <<  c_graduated.Access_Value() << endl; cout << &quot;The number of students delayed this semester: &quot;  <<  c_delayed.Access_Value() << endl; return; }
See example on page 405 and 406
Constructors A constructor function is any function that has the same name as it s class. Constructors can be over loaded Constructor has no return type If no constructor is written compiler will provide default constructor
Default Constructor Any constructor that does not require any parameters when it is called. This can be because no parameters are declared All parameters have been given default values. For example Date(int=7, int =4, int = 2001 )
Destructor The name of the destructor for a class is the tilde(~) character followed by the name of the class. There can be only one destructor Destructor take no parameter and it has no return value Destructor is called when a class object is destroyed. A default destructor is provided if not written by programmer.
ANOTHER EXAMPLE: PROBLEM : USING FLOATING POINT NOTATION TO REPRESENT FRACTIONS MAY PRODUCE APPROXIMATE RESULTS.  FOR EXAMPLE, THE RATIONAL NUMBER 1/3 IS 0.33333. REGARDLESS OF THE NUMBER OF ACCURATE DIGITS, IT WOULD BE IMPOSSIBLE TO PRECISELY REPRESENT SUCH A NUMBER.  DESIGN, DEVELOP AND IMPLEMENT A SYSTEM TO REPRESENT FRACTIONS ACCURATELY. AS AN EXAMPLE, WE WILL IMPLEMENT THE ADDITION OPERATION ONLY.
ANALYSIS : 1. DISCUSSION THE OPERATIONS TO BE PERFORMED ON THE Fraction CLASS ARE:  CONSTRUCT AND INITIALIZE A NEW FRACTION OBJECT DISPLAY A FRACTION GET A FRACTION ADD TWO FRACTIONS (RESULTING IN THIRD FRACTION) CONVERT TO FLOAT POINT NOTATION
2. CLASS SPECIFICATION A)  PUBLIC CONSTRUCT: Fraction(int n, int d = 1); Fraction(); void Get(); void Show(); double Evaluate(); B)  PRIVATE int numerator; int denominator; C)  FRIEND friend Fraction operator+ (Fraction f1,  Fraction f2);
NEW CONCEPTS FRIEND FUNCTIONS, OPERATOR OVERLOADING, AND CONSTRUCTORS
class  <class_name> { friend  <function prototype> ; // optional public: <public data structures> // optional <constructors> // optional <function prototypes> // optional private: // optional <data structures> // optional <function prototypes> // optional };
class Fraction { // operator overload, so we can do fractional arithmetic  // using a familiar operator, the  &quot;+&quot;  sign friend Fraction operator+ (Fraction f1, Fraction f2); public: : private: : }; FRIEND FUNCTIONS AND OPERATOR OVERLOADING
class Fraction { : public: Fraction(int n, int d = 1); // constructor Fraction();  // another constructor : private: : }; CONSTRUCTORS
// File: Fraction.h // The class declaration for fractions is included in this // header file. We represent a fraction using a pair of integers: // the numerator (top part) and denominator (bottom part). // This class definition includes more than the rational  // numbers, since the number infinity is permitted (a fraction // with a zero denominator--except 0/0)
class Fraction { // operator overload, so we can do fractional arithmetic  // using a familiar operator , the  &quot;+&quot;  sign   friend Fraction operator+ (Fraction f1, Fraction f2); public: Fraction(int n, int d = 1);  // constructor // Set numerator = n, denominator = d // if no second argument, default to 1 // another constructor: Fraction(); // Set numerator = 0, denominator = 1 void Get(); // Get a fraction from keyboard void Show(); // Display a fraction on screen double Evaluate(); // Return the decimal value of a fraction private: int numerator; // top part int denominator; // bottom part };
// File: Fraction.cpp // The class definition for fractions #include <iostream.h> #include &quot;Fraction.h&quot; Fraction operator+ (Fraction f1, Fraction f2) // Override of operator &quot;+&quot; for fraction addition { Fraction r;   // the return value of f1 + f2   // compute numerator r.numerator =  (f1.numerator * f2.denominator) +    (f2.numerator * f1.denominator);    // compute denominator r.denominator = f1.denominator * f2.denominator; return r;   // return the result }
Fraction::Fraction(int n, int d) // A Fraction constructor which allows the numerator and // denominator to be specified { numerator = n; denominator = d; }
Fraction::Fraction() // Another constructor. If no arguments specified, default to 0/1  { numerator = 0; denominator = 1; }
void Fraction::Get() // Get a fraction from standard input, in the form  // &quot;numerator/denominator&quot; { char div_sign; // used to consume the '/' character during input cin >> numerator >> div_sign >> denominator; }
void Fraction::Show()  // Display a fraction, in the form &quot;numerator/denominator&quot; { cout << numerator << '/' << denominator; }
double Fraction::Evaluate()  // Calculates and returns the decimal value of a fraction { double n = numerator; // convert numerator to float  double d = denominator; // convert denominator to float  return (n / d); // return float representation }
// File: TestFraction.cpp // Test the Fraction class #include <iostream.h> // for output #include &quot;Fraction.h&quot; // for Fraction declarations void main() { // Fraction constructors Fraction f1(3, 2), f2(4), f3, f4; // Display the fractions  cout << endl << &quot;The fraction f1 is &quot;; f1.Show(); cout << endl << &quot;The fraction f2 is &quot;; f2.Show(); cout << endl << &quot;The fraction f3 is &quot;; f3.Show(); // Get and display a fraction cout << endl << &quot;Enter a fraction of your own: &quot;; f3.Get(); cout << endl << &quot;You entered &quot;; f3.Show();
// Add two Fractions using the overloaded operator f4 = f1 + f3; // Display the fractions and result cout << endl << endl << &quot;The sum of &quot;; f1.Show(); cout << &quot; and &quot;; f3.Show(); cout << &quot; is &quot;; f4.Show(); // Find and display the floating-point value of the Fraction cout << endl << &quot;The value of this fraction is &quot;  << f4.Evaluate() << endl; }

More Related Content

What's hot (20)

PPTX
Pointers
Munazza-Mah-Jabeen
 
PPTX
constructors and destructors in c++
HalaiHansaika
 
PPT
Basic c#
kishore4268
 
PPTX
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Abu Saleh
 
PPTX
C introduction by thooyavan
Thooyavan Venkatachalam
 
PPT
C++ Overview
kelleyc3
 
PDF
Templates
Pranali Chaudhari
 
PPT
C++: Constructor, Copy Constructor and Assignment operator
Jussi Pohjolainen
 
PDF
Writing Node.js Bindings - General Principles - Gabriel Schulhof
WithTheBest
 
PPTX
Templates presentation
malaybpramanik
 
PPTX
Abstract Base Class and Polymorphism in C++
Liju Thomas
 
PDF
Chapter27 polymorphism-virtual-function-abstract-class
Deepak Singh
 
PPT
Visula C# Programming Lecture 6
Abou Bakr Ashraf
 
PDF
C Recursion, Pointers, Dynamic memory management
Sreedhar Chowdam
 
PPTX
C sharp part 001
Ralph Weber
 
PPTX
Moving Average Filter in C
Colin
 
PDF
Assignment2
Sunita Milind Dol
 
PPT
pointers, virtual functions and polymorphisms in c++ || in cpp
gourav kottawar
 
PDF
Object Oriented Programming using C++ Part III
Ajit Nayak
 
constructors and destructors in c++
HalaiHansaika
 
Basic c#
kishore4268
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Abu Saleh
 
C introduction by thooyavan
Thooyavan Venkatachalam
 
C++ Overview
kelleyc3
 
C++: Constructor, Copy Constructor and Assignment operator
Jussi Pohjolainen
 
Writing Node.js Bindings - General Principles - Gabriel Schulhof
WithTheBest
 
Templates presentation
malaybpramanik
 
Abstract Base Class and Polymorphism in C++
Liju Thomas
 
Chapter27 polymorphism-virtual-function-abstract-class
Deepak Singh
 
Visula C# Programming Lecture 6
Abou Bakr Ashraf
 
C Recursion, Pointers, Dynamic memory management
Sreedhar Chowdam
 
C sharp part 001
Ralph Weber
 
Moving Average Filter in C
Colin
 
Assignment2
Sunita Milind Dol
 
pointers, virtual functions and polymorphisms in c++ || in cpp
gourav kottawar
 
Object Oriented Programming using C++ Part III
Ajit Nayak
 

Viewers also liked (20)

PDF
Kivimäki: Kouluterveyskysely
Kouluterveyskysely
 
PDF
АО "Самрук-Қазына": Проект стратегии развития
АО "Самрук-Казына"
 
PDF
Building a Website from Planning to Photoshop Mockup to HTML/CSS
hstryk
 
PPTX
Romania, my country, Dana B
balada65
 
PPT
Power Notes Atomic Structure Day 3
jmori1
 
PPT
Power Notes Atomic Structure
jmori1
 
PPTX
S6 w2 chi square
Rachel Chung
 
PPTX
Track2 -刘希斌----c ie-net-openstack-2012-apac
OpenCity Community
 
PDF
Payfirma Mobile Payment App
Payfirma
 
KEY
God's Hobby
Doug Rittenhouse
 
PDF
Software development company
Creative Technosoft Systems
 
PPTX
TheBehaviourReport.com Profile
Oscar Habeenzu
 
PDF
Betiad
betiad
 
PPTX
Cosug status-final
OpenCity Community
 
PPTX
Heaven - escena baralla al parc
mvinola2
 
DOCX
India
mail2sarun
 
PDF
PFCongres 2012 - Rock Solid Deployment of PHP Apps
Pablo Godel
 
PDF
Wind Lift Brochure Web
gm330
 
PPSX
Anivesario wanderlan pereira lima
angical-piaui
 
PPT
C1320prespost
FALLEE31188
 
Kivimäki: Kouluterveyskysely
Kouluterveyskysely
 
АО "Самрук-Қазына": Проект стратегии развития
АО "Самрук-Казына"
 
Building a Website from Planning to Photoshop Mockup to HTML/CSS
hstryk
 
Romania, my country, Dana B
balada65
 
Power Notes Atomic Structure Day 3
jmori1
 
Power Notes Atomic Structure
jmori1
 
S6 w2 chi square
Rachel Chung
 
Track2 -刘希斌----c ie-net-openstack-2012-apac
OpenCity Community
 
Payfirma Mobile Payment App
Payfirma
 
God's Hobby
Doug Rittenhouse
 
Software development company
Creative Technosoft Systems
 
TheBehaviourReport.com Profile
Oscar Habeenzu
 
Betiad
betiad
 
Cosug status-final
OpenCity Community
 
Heaven - escena baralla al parc
mvinola2
 
India
mail2sarun
 
PFCongres 2012 - Rock Solid Deployment of PHP Apps
Pablo Godel
 
Wind Lift Brochure Web
gm330
 
Anivesario wanderlan pereira lima
angical-piaui
 
C1320prespost
FALLEE31188
 
Ad

Similar to C++lecture9 (20)

PPT
Classes, objects and methods
farhan amjad
 
PPTX
class and objects
Payel Guria
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Implementation of oop concept in c++
Swarup Kumar Boro
 
PPTX
Chp 3 C++ for newbies, learn fast and earn fast
nhbinaaa112
 
PDF
Op ps
Shehzad Rizwan
 
PPTX
CPP Homework Help
C++ Homework Help
 
PDF
02.adt
Aditya Asmara
 
PPTX
Data types
Nokesh Prabhakar
 
PPTX
Structured Languages
Mufaddal Nullwala
 
PPTX
C++ Object Oriented Programming Lecture Slides for Students
MuhammadAli224595
 
PDF
Classes
Swarup Boro
 
PDF
Ds lab handouts
Ayesha Bhatti
 
PPT
Lecture 3 c++
emailharmeet
 
DOC
Pads lab manual final
AhalyaR
 
PPT
w10 (1).ppt
amal68766
 
PDF
C++ normal assignments by maharshi_jd.pdf
maharshi1731
 
PPT
Object Oriented Programming Examples with explanation
ulhaq18
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Classes, objects and methods
farhan amjad
 
class and objects
Payel Guria
 
Object Oriented Programming (OOP) using C++ - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Implementation of oop concept in c++
Swarup Kumar Boro
 
Chp 3 C++ for newbies, learn fast and earn fast
nhbinaaa112
 
CPP Homework Help
C++ Homework Help
 
Data types
Nokesh Prabhakar
 
Structured Languages
Mufaddal Nullwala
 
C++ Object Oriented Programming Lecture Slides for Students
MuhammadAli224595
 
Classes
Swarup Boro
 
Ds lab handouts
Ayesha Bhatti
 
Lecture 3 c++
emailharmeet
 
Pads lab manual final
AhalyaR
 
w10 (1).ppt
amal68766
 
C++ normal assignments by maharshi_jd.pdf
maharshi1731
 
Object Oriented Programming Examples with explanation
ulhaq18
 
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Ad

More from FALLEE31188 (20)

PPT
Lecture4
FALLEE31188
 
PPT
Lecture2
FALLEE31188
 
PPT
L16
FALLEE31188
 
PPTX
Inheritance
FALLEE31188
 
PDF
Inheritance
FALLEE31188
 
PPT
Functions
FALLEE31188
 
DOC
Field name
FALLEE31188
 
PPT
Encapsulation
FALLEE31188
 
PPT
Cpp tutorial
FALLEE31188
 
PPT
Cis068 08
FALLEE31188
 
PPT
Chapter14
FALLEE31188
 
PPT
Chapt03
FALLEE31188
 
PPT
C++ polymorphism
FALLEE31188
 
PPT
C++ classes tutorials
FALLEE31188
 
PPT
Brookshear 06
FALLEE31188
 
PPT
Book ppt
FALLEE31188
 
PPTX
Assignment 2
FALLEE31188
 
PPTX
Assignment
FALLEE31188
 
PPT
5 2
FALLEE31188
 
Lecture4
FALLEE31188
 
Lecture2
FALLEE31188
 
Inheritance
FALLEE31188
 
Inheritance
FALLEE31188
 
Functions
FALLEE31188
 
Field name
FALLEE31188
 
Encapsulation
FALLEE31188
 
Cpp tutorial
FALLEE31188
 
Cis068 08
FALLEE31188
 
Chapter14
FALLEE31188
 
Chapt03
FALLEE31188
 
C++ polymorphism
FALLEE31188
 
C++ classes tutorials
FALLEE31188
 
Brookshear 06
FALLEE31188
 
Book ppt
FALLEE31188
 
Assignment 2
FALLEE31188
 
Assignment
FALLEE31188
 

Recently uploaded (20)

PPTX
I INCLUDED THIS TOPIC IS INTELLIGENCE DEFINITION, MEANING, INDIVIDUAL DIFFERE...
parmarjuli1412
 
PPTX
Qweb Templates and Operations in Odoo 18
Celine George
 
PPTX
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
PDF
Module 1: Determinants of Health [Tutorial Slides]
JonathanHallett4
 
PPTX
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
PPTX
YSPH VMOC Special Report - Measles Outbreak Southwest US 7-20-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
PPTX
Nutrition Quiz bee for elementary 2025 1.pptx
RichellMarianoPugal
 
PPTX
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
PDF
EXCRETION-STRUCTURE OF NEPHRON,URINE FORMATION
raviralanaresh2
 
PPTX
Electrophysiology_of_Heart. Electrophysiology studies in Cardiovascular syste...
Rajshri Ghogare
 
PPTX
quizbeenutirtion-230726075512-0387d08e.pptx
domingoriahlyne
 
PPTX
Virus sequence retrieval from NCBI database
yamunaK13
 
PPT
DRUGS USED IN THERAPY OF SHOCK, Shock Therapy, Treatment or management of shock
Rajshri Ghogare
 
PPTX
Unlock the Power of Cursor AI: MuleSoft Integrations
Veera Pallapu
 
PPTX
GENERAL METHODS OF ISOLATION AND PURIFICATION OF MARINE__MPHARM.pptx
SHAHEEN SHABBIR
 
PPTX
HERNIA: INGUINAL HERNIA, UMBLICAL HERNIA.pptx
PRADEEP ABOTHU
 
PPTX
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
PPTX
MALABSORPTION SYNDROME: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PPTX
DIARRHOEA & DEHYDRATION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
I INCLUDED THIS TOPIC IS INTELLIGENCE DEFINITION, MEANING, INDIVIDUAL DIFFERE...
parmarjuli1412
 
Qweb Templates and Operations in Odoo 18
Celine George
 
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
Module 1: Determinants of Health [Tutorial Slides]
JonathanHallett4
 
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 7-20-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Nutrition Quiz bee for elementary 2025 1.pptx
RichellMarianoPugal
 
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
EXCRETION-STRUCTURE OF NEPHRON,URINE FORMATION
raviralanaresh2
 
Electrophysiology_of_Heart. Electrophysiology studies in Cardiovascular syste...
Rajshri Ghogare
 
quizbeenutirtion-230726075512-0387d08e.pptx
domingoriahlyne
 
Virus sequence retrieval from NCBI database
yamunaK13
 
DRUGS USED IN THERAPY OF SHOCK, Shock Therapy, Treatment or management of shock
Rajshri Ghogare
 
Unlock the Power of Cursor AI: MuleSoft Integrations
Veera Pallapu
 
GENERAL METHODS OF ISOLATION AND PURIFICATION OF MARINE__MPHARM.pptx
SHAHEEN SHABBIR
 
HERNIA: INGUINAL HERNIA, UMBLICAL HERNIA.pptx
PRADEEP ABOTHU
 
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
MALABSORPTION SYNDROME: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
DIARRHOEA & DEHYDRATION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 

C++lecture9

  • 1. DATA ABSTRACTION: USER DEFINED TYPES AND THE CLASS
  • 2. DATA TYPES A DATA TYPE IS A FORMAL DESCRIPTION OF: 1. THE DOMAIN THAT AN OBJECT OF THAT TYPE CAN HAVE. 2. THE BASIC SET OF OPERATIONS THAT CAN BE APPLIED TO VALUES OF THAT TYPE. 3. DATA REPRESENTATION.
  • 3. THE FORMAL DESCRIPTION OF int AND float VALUES AND THE ALLOWABLE OPERATIONS ON SUCH DATA TYPE COME FROM MATHEMATICS. THE OPERATIONS ARE: + , - , * , AND / . THE RANGE OF VALUES CAN BE LISTED AS INT_MIN TO INT_MAX .
  • 4. THE VALUES OF TYPE char ARE THE ALPHANUMERIC CHARACTERS OF THE ASCII SET. MEMBERS ARE ORDERED IN RELATION TO EACH OTHER. '0' < '1' < '2' < ... '7' < '8' < '9' AND 'a' < 'b' < 'c'< ... 'x' < 'y' < 'z'
  • 5. AN OBJECT OF THE BASIC TYPES int , float , AND char CAN HOLD ONLY ONE VALUE. EACH ONE IS MADE UP OF INDIVISIBLE, OR ATOMIC ELEMENTS. int AND char SHARE A COMMON PROPERTY: THEY ARE ORDINAL TYPES. THE VALUES OF EACH TYPE CAN BE LISTED IN A SEQUENCE.
  • 6. IN SOME INSTANCES, THE BASIC TYPES MAY NOT BE SUITABLE FOR DATA REPRESENTATION, OR SIMPLY NOT QUITE READABLE. C++ HAS A MECHANISM FOR ALLOWING TO CREATE NEW DATA TYPES. THAT IS, THE PROGRAMMERS DECLARE AND DEFINE NEW TYPES. DATA ABSTRACTION: SIMPLE TYPES (USER-DEFINED)
  • 7. EXAMPLE: TYPE DEFINITION typedef existing_type_name new_type_name ;
  • 8. A SIMULATION OF THE TYPE Logical : typedef int Logical; const Logical TRUE = 1; const Logical FALSE = 0; : Logical positive; : positive = TRUE; // initialize flag
  • 9. MORE ON DATA ABSTRACTION ABSTRACT DATA TYPES PROVIDE FOR THE ABILITY TO MODEL THE DOMAIN AND OPERATIONS OF DATA WITHOUT ANY CONCERN ABOUT IMPLEMENTATION.
  • 10. THE CASE OF THE &quot;COUNTER&quot; A COUNTER IS A SIMPLE INTEGER VARIABLE. ITS VALUE IS CHANGED AND ACCESSED DEPENDING ON SOME OTHER TASK.
  • 11. COMMON OPERATIONS PERFORMED (ON THE INTEGER VARIABLE) ARE: 1. CLEAR (START AT SOME INITIAL VALUE) 2. ALTER THE VALUE TO KEEP TRACK OF TASK (INCREMENT) 3. ALTER THE VALUE TO KEEP TRACK OF TASK (DECREMENT) 4. EXAMINE OR PRINT THE CURRENT VALUE (ACCESS)
  • 12. EXAMPLE: PROBLEM : GRADUATION CERTIFICATION REFERS TO EVALUATING EARNED CREDITS TO ASSURE THAT STUDENTS HAVE SATISFIED CURRICULUM REQUIREMENTS. SOME STUDENTS DO, SOME DO NOT. DEVELOP AND IMPLEMENT A SYSTEM THAT KEEPS TRACK OF THOSE STUDENTS WHO ARE GRADUATING AND THOSE THAT ARE DELAYED BASED ON NUMBER OF CREDITS EARNED.
  • 13. ANALYSIS : 1. DISCUSSION (ONLY REGARDING COUNTER) THE OPERATIONS TO BE PERFORMED ON THE COUNTER ARE: INITIALIZE INCREMENT DECREMENT ACCESS
  • 14. 2. SPECIFICATION (ONLY REGARDING COUNTER) a) OPERATIONS void Initialize(int); void Increment(); void Decrement(); int Access_Value(); b) DATA int value;
  • 15. GRAD-VALID VALIDATE GET_CREDITS PRINT RESULT LEVEL 0 LEVEL 1 3. STRUCTURE CHART
  • 17. RELATIONSHIP BETWEEN DATA AND OPERATIONS: SEPARATE ENTITIES PROCESS A DATA STRUCTURES CONTROL STRUCTURES PROCESS D PROCESS C PROCESS B
  • 18. ALTERNATIVE REPRESENTATION THE CLASS , A SET OF OBJECTS, ALLOWS FOR THE REPRESENTATION OF DATA AND OPERATIONS INTO A COHESIVE UNIT.
  • 19. RELATIONSHIP BETWEEN DATA AND OPERATIONS: A COHERENT UNIT CONTROL STRUCTURES AND DATA STRUCTURES PROCESS A PROCESS D PROCESS C PROCESS B DATA
  • 20. THE C++ CLASS A MECHANISM TO MODEL OBJECTS WITH MULTIPLE ATTRIBUTES. THE C++ CLASS ALLOWS FOR THE DEFINITION A NEW TYPE OF DATA ACCORDING TO THE NEEDS OF THE PROBLEM, AND TO DEFINE OPERATIONS (METHODS) TO ACT UPON THE TYPE (ABSTRACT DATA TYPING).
  • 21. INFORMATION HIDING THE ENCAPSULATION OF IMPLEMENTATION DETAILS. PRIVATE CODE AND DATA CANNOT BE ACCESSED DIRECTLY.
  • 22. CLASS SYNTAX class <class_name> { public: <public declaration list> private: <private declaration list> };
  • 23. class <class_name> { public: <public data structures> // optional <constructors> // optional <function prototypes> // optional private: // optional <private data structures> // optional <function prototypes> // optional };
  • 24. EXAMPLE 1 // class declaration section class Date { private: int month; //a data member int day; // a data member int year; // a data member public: Date( int = 11, int = 16, int = 2001 ); // the constructor void setdate(int, int, int); // a member function void showdate(); // a member function } ;
  • 25. SYNTAX OF DEFINING MEMBER FUNCTIONS <return_type> <class_name> :: <function_name> ( <parameter_list> ) { <function member body> }
  • 26. EXAMPLE 1 // class implementation section Date::Date( int mm, int dd, int yyyy) { month = mm; day = dd; year = yyyy; } void Date:: setdate(int mm, int dd, int yyyy) { month = mm; day = dd; year = yyyy; return ; }
  • 27. void Date::showdate() { cout<< “ The date is “; cout<< setfill ( ‘0’) << setw(2)<< month << ‘/ ‘ << setw(2)<< day << ‘/ ‘ << setw(2)<< year % 100 ; // extract last //two year digits cout<< ednl ; return ; }
  • 28. Class Scope and Accessing Class Members A class data members and function members belong to that class scope. Nonmember functions are defined as file scope. Within class scope members are accessible by using their name Outside class scope, class members are referenced through one of the handles on an object – an object name, a reference to an object or pointer to an object. Variable defined in member function has function scope. You can hide data member in a function by using same name.
  • 29. Once the class has been defined, it can be used as a type in object, array and pointer definitions. For example class Date can be used in the following main function as follows
  • 30. int main () { Date a, b, c(4, 1, 1998) // declare three objects – //initialize one of them b.setdate(12, 25, 2002);//assign values to b’s data members a.Showdate( ); // display object a’s values b.Showdate( ); // display object b’s values c.Showdate( ); // display object c’s values return 0 ; } /*output The date is 07/04/01 The date is 12/25/02 The date is 04/01/98 */
  • 31. IMPLEMENTATION: THE Counter CLASS // File: Counter.h #include <limits.h> // contains definitions of // INT_MAX and INT_MIN class Counter { public: // member functions void Initialize(int init_value); // initialize counter void Increment(); // increment counter void Decrement(); // decrement counter int Access_Value(); // return current counter // value private: // data members int value; };
  • 32. void Counter::Initialize(int init_value) // initialize counter { value = init_value; } // Initialize() void Counter::Increment() // increment counter { if (value < INT_MAX) value++; else cerr << &quot;Counter overflow. Increment ignored.&quot; << endl; } // Increment()
  • 33. void Counter::Decrement() // decrement counter { if (value > INT_MIN) value--; else cerr << &quot;Counter underflow. Decrement ignored.&quot; << endl; } // Decrement() int Counter::Access_Value() // return current counter value { return value; } // Access_Value()
  • 34. #include <iostream.h> #include &quot;Counter.h&quot; void main() { // Minimum credits for graduation const int GRAD_LEVEL = 130; // local objects of class Counter Counter c_graduated; Counter c_delayed; // local data int class_size, number_of_credits; int i; // get the graduating class size cout << &quot;Enter the class size: &quot;; cin >> class_size; IMPLEMENTATION (USING THE Counter CLASS)
  • 35. // initialize counter values c_graduated.Initialize(0); c_delayed.Initialize(class_size); // use of Increment() and Decrement() for (i = 0; i < class_size; i++) { cout << &quot;Please enter the number of validated credits: &quot;; cin >> number_of_credits; if (number_of_credits >= GRAD_LEVEL) { c_graduated.Increment(); c_delayed.Decrement(); } } // print results using Access_value() cout << &quot;The number of students graduating this semester: &quot; << c_graduated.Access_Value() << endl; cout << &quot;The number of students delayed this semester: &quot; << c_delayed.Access_Value() << endl; return; }
  • 36. See example on page 405 and 406
  • 37. Constructors A constructor function is any function that has the same name as it s class. Constructors can be over loaded Constructor has no return type If no constructor is written compiler will provide default constructor
  • 38. Default Constructor Any constructor that does not require any parameters when it is called. This can be because no parameters are declared All parameters have been given default values. For example Date(int=7, int =4, int = 2001 )
  • 39. Destructor The name of the destructor for a class is the tilde(~) character followed by the name of the class. There can be only one destructor Destructor take no parameter and it has no return value Destructor is called when a class object is destroyed. A default destructor is provided if not written by programmer.
  • 40. ANOTHER EXAMPLE: PROBLEM : USING FLOATING POINT NOTATION TO REPRESENT FRACTIONS MAY PRODUCE APPROXIMATE RESULTS. FOR EXAMPLE, THE RATIONAL NUMBER 1/3 IS 0.33333. REGARDLESS OF THE NUMBER OF ACCURATE DIGITS, IT WOULD BE IMPOSSIBLE TO PRECISELY REPRESENT SUCH A NUMBER. DESIGN, DEVELOP AND IMPLEMENT A SYSTEM TO REPRESENT FRACTIONS ACCURATELY. AS AN EXAMPLE, WE WILL IMPLEMENT THE ADDITION OPERATION ONLY.
  • 41. ANALYSIS : 1. DISCUSSION THE OPERATIONS TO BE PERFORMED ON THE Fraction CLASS ARE: CONSTRUCT AND INITIALIZE A NEW FRACTION OBJECT DISPLAY A FRACTION GET A FRACTION ADD TWO FRACTIONS (RESULTING IN THIRD FRACTION) CONVERT TO FLOAT POINT NOTATION
  • 42. 2. CLASS SPECIFICATION A) PUBLIC CONSTRUCT: Fraction(int n, int d = 1); Fraction(); void Get(); void Show(); double Evaluate(); B) PRIVATE int numerator; int denominator; C) FRIEND friend Fraction operator+ (Fraction f1, Fraction f2);
  • 43. NEW CONCEPTS FRIEND FUNCTIONS, OPERATOR OVERLOADING, AND CONSTRUCTORS
  • 44. class <class_name> { friend <function prototype> ; // optional public: <public data structures> // optional <constructors> // optional <function prototypes> // optional private: // optional <data structures> // optional <function prototypes> // optional };
  • 45. class Fraction { // operator overload, so we can do fractional arithmetic // using a familiar operator, the &quot;+&quot; sign friend Fraction operator+ (Fraction f1, Fraction f2); public: : private: : }; FRIEND FUNCTIONS AND OPERATOR OVERLOADING
  • 46. class Fraction { : public: Fraction(int n, int d = 1); // constructor Fraction(); // another constructor : private: : }; CONSTRUCTORS
  • 47. // File: Fraction.h // The class declaration for fractions is included in this // header file. We represent a fraction using a pair of integers: // the numerator (top part) and denominator (bottom part). // This class definition includes more than the rational // numbers, since the number infinity is permitted (a fraction // with a zero denominator--except 0/0)
  • 48. class Fraction { // operator overload, so we can do fractional arithmetic // using a familiar operator , the &quot;+&quot; sign friend Fraction operator+ (Fraction f1, Fraction f2); public: Fraction(int n, int d = 1); // constructor // Set numerator = n, denominator = d // if no second argument, default to 1 // another constructor: Fraction(); // Set numerator = 0, denominator = 1 void Get(); // Get a fraction from keyboard void Show(); // Display a fraction on screen double Evaluate(); // Return the decimal value of a fraction private: int numerator; // top part int denominator; // bottom part };
  • 49. // File: Fraction.cpp // The class definition for fractions #include <iostream.h> #include &quot;Fraction.h&quot; Fraction operator+ (Fraction f1, Fraction f2) // Override of operator &quot;+&quot; for fraction addition { Fraction r; // the return value of f1 + f2 // compute numerator r.numerator = (f1.numerator * f2.denominator) + (f2.numerator * f1.denominator); // compute denominator r.denominator = f1.denominator * f2.denominator; return r; // return the result }
  • 50. Fraction::Fraction(int n, int d) // A Fraction constructor which allows the numerator and // denominator to be specified { numerator = n; denominator = d; }
  • 51. Fraction::Fraction() // Another constructor. If no arguments specified, default to 0/1 { numerator = 0; denominator = 1; }
  • 52. void Fraction::Get() // Get a fraction from standard input, in the form // &quot;numerator/denominator&quot; { char div_sign; // used to consume the '/' character during input cin >> numerator >> div_sign >> denominator; }
  • 53. void Fraction::Show() // Display a fraction, in the form &quot;numerator/denominator&quot; { cout << numerator << '/' << denominator; }
  • 54. double Fraction::Evaluate() // Calculates and returns the decimal value of a fraction { double n = numerator; // convert numerator to float double d = denominator; // convert denominator to float return (n / d); // return float representation }
  • 55. // File: TestFraction.cpp // Test the Fraction class #include <iostream.h> // for output #include &quot;Fraction.h&quot; // for Fraction declarations void main() { // Fraction constructors Fraction f1(3, 2), f2(4), f3, f4; // Display the fractions cout << endl << &quot;The fraction f1 is &quot;; f1.Show(); cout << endl << &quot;The fraction f2 is &quot;; f2.Show(); cout << endl << &quot;The fraction f3 is &quot;; f3.Show(); // Get and display a fraction cout << endl << &quot;Enter a fraction of your own: &quot;; f3.Get(); cout << endl << &quot;You entered &quot;; f3.Show();
  • 56. // Add two Fractions using the overloaded operator f4 = f1 + f3; // Display the fractions and result cout << endl << endl << &quot;The sum of &quot;; f1.Show(); cout << &quot; and &quot;; f3.Show(); cout << &quot; is &quot;; f4.Show(); // Find and display the floating-point value of the Fraction cout << endl << &quot;The value of this fraction is &quot; << f4.Evaluate() << endl; }

Editor's Notes

  • #23: Member access specifiers are always followed by a colon (:) and can appear multiple times in any order.
  • #24: CONSTRUCTOR: defining, call, overloading, no return type.