SlideShare una empresa de Scribd logo
1 de 13
Descargar para leer sin conexión
Classes and Objects in C++




                    Data Types
• Recall that C++ has predefined data types,
  such as int
• int x; // Creates a specific instance of an
         // integer named x
• C++ also predefines operations that can
  be used on integers, such as + and *




                       Classes
• Sometimes, a programmer will want to
  define a custom "thing" and the operations
  that can be performed on that "thing"
• A class is the definition
• An object is a particular instance of a class
• Classes contain
  – data, called members
  – functions, called methods




                                                  1
Class Declaration
class Class_name
{
    public:
        member (data) definitions
        method (function) definitions
    private:
        member (data) definitions
        method (function) definitions
};
// order of public and private can be reversed
// data is seldom public
// note semicolon after }




                    Public and Private
• Public members and methods can be
  accessed from outside the class and
  provide the interface
• Private members and methods cannot be
  accessed from outside the class




                         Data Hiding
• Recall that many programmers can each write a
  small piece of a large program
• Need to have some way to define how other
  programmers can use your stuff
   – Public methods are the only way for any other code to
     access the class
• Need to have some way to keep other
  programmers from messing up your stuff
   – Private methods and members cannot be accessed
     from outside the class




                                                             2
Reusability and
                                Changeability
• Writing programs is expensive, so
  organizations try to reuse code and avoid
  changing it
• If classes are well written, they can be
  reused in several programs
• Also, the internals of a class can be
  rewritten - as long as the interface does not
  change, programs that use that class do
  not need to be changed




                                      Example 1
Create a counter. Other parts of the
 program should be able to increment the
 counter and read the counter




class Counter {
    public:
          // constructor to initialize the object - note no function type
          Counter ( ) {
                    currentcount = 0;
          };
          // increment the counter
          void count( ) {
                    currentcount++;
          };
          // get the current value of the counter
          int readcounter( ) {
                    return currentcount;
          };
    private:
          int currentcount;
};




                                                                            3
Constructors
• Constructors are methods that initialize an
  object
  – Must have same name as the class
  – Declaration is odd - no function type
           Counter ( ) { ..... }
  – Not required, but should be used when data
    needs to be initialized
  – Never explicitly called - automatically called
    when an object of this class is declared




                      Destructors
• Destructors are methods that clean up
  when an object is destroyed
  – Must have the same name as the class, but
    with a ~ in front
  – No function type in declaration
     ~ Counter ( ) { ..... }
  – Also not required, but should be provided if
    necessary to release memory, for example
  – Never explicitly called - automatically called
    when an object of this class is destroyed




               Creating an Object
• To create an instance of class counter
  (called an object) declare it as you would
  any other variable
  Class_name object_name(s);
  – This automatically calls the constructor
    method to initialize the object


Counter my_counter;




                                                     4
Using an Object
• Using a public method is similar to a
  function call
  object_name.method_name (arguments)

 my_counter.count( );
 int current = my_counter.readcounter( );




                Using an Object
• Common error - using the class name
  instead of the object name
   Counter.count ( );    // WRONG!
   my_counter.count ( ); // RIGHT!
• Common error - trying to use private
  members or methods outside the class
   cout << currentcount ; // WRONG!
   cout << my_counter.readcounter ( ); // RIGHT!




           Putting It All Together
#include <iostream>
using namespace std;




                                                   5
class Counter {
    public:
          // constructor to initialize the object
          Counter ( ) {
                    currentcount = 0;
          };
          // increment the counter
          void count( ) {
                    currentcount++;
          };
          // get the current value of the counter
          int readcounter( ) {
                    return currentcount;
          };
    private:
          int currentcount;
};




int main ( )
{
// declare two objects
Counter first_counter, second_counter;

// increment counters
first_counter.count( );
second_counter.count( );
second_counter.count( );

//display counts
cout << "first counter is " << first_counter.readcounter( ) << endl;
cout << "second counter is " << second_counter.readcounter( ) << endl;

return 0;
}




                                          Output
first counter is 1
second counter is 2




                                                                         6
Global Scope
• Anything declared outside of a function,
  such as the class in this example or a
  variable, can be used by any function in
  the program and is global
• Anything declared inside a function can
  only be used in that function
• Usual to declare classes to be global
• Global variables are bad programming
  practice and should be avoided




              Function Prototypes in
               Class Declarations
• In the previous example, the functions
  (methods) were completely declared within
  the class declaration
• Often more readable to put only function
  prototypes in the class declaration and put
  the method implementations later
• use class_name::method_name when
  declaring the methods
• This is the usual convention




class Counter {             Counter::Counter ( ) {

  public:                       currentcount = 0;
                            }
      Counter ( );
      void count( );        void Counter::count ( ){
      int readcounter( );       currentcount ++;
  private:                  }
      int currentcount;
                            int Counter::readcounter ( ){
}
                                return currentcount ;
                            }




                                                            7
Identifying Classes
• Often, it is not immediately obvious what
  the classes should be to solve a particular
  problem
• One hint is to consider some of the nouns
  in the problem statement to be the
  classes. The verbs in the problem
  statement will then be the methods.




                           Example 2
• Write a program that manages a
  checkbook. The user should be able to
  set the original account balance, deposit
  money in the account, remove money
  when a check is written, and query the
  current balance.




                           Example 2
class CheckBook
   public methods are init, deposit, check, and query
Pseudocode for main program
   display menu and get user choice
   while user does not choose quit
       Set starting balance: get the amount, call init
       Deposit: get amount, call deposit
       Write a check: get amount, call check
       Balance: call query, display balance
       display menu and get user choice




                                                         8
Example 2 Program
#include <iostream>
#include <iomanip>
using namespace std;




                          Class Declaration
class CheckBook{
   private:
       float balance;
   public:
       CheckBook ( );                     //constructor
       void init (float);                 // set balance
       void deposit (float);              //add deposit
       void check (float);                //subtract check
       float query ( );                   //get balance
};




                              Class Method
                              Declarations
CheckBook::CheckBook ( ) {
         balance = 0;
}
void CheckBook::init (float money) {
         balance = money;
}
void CheckBook::deposit (float money) {
         balance = balance + money;
}
void CheckBook:: check (float money){
         balance = balance - money;
}
float CheckBook:: query ( ){
         return balance;
}




                                                             9
Menu Function
int menu ( ) {
   int choice;
   cout << "0: Quit" << endl;
   cout << "1: Set initial balance" << endl;
   cout << "2: Deposit" << endl;
   cout << "3: Deduct a check" << endl;
   cout << "4: Find current balance" << endl;
   cout << "Please enter your selection: ";
   cin >> choice;
   return choice;
}




int main ( )
{
     int sel = menu ( ); // get initial user input
     float amount;
     CheckBook my_checks; // declare object
     // loop until user enters 0 to quit
     while (sel != 0) {
             // set initial balance
             if (sel == 1) {
                          cout << "Please enter initial balance: ";
                          cin >> amount;
                          my_checks.init(amount );
             }
             // deposit
             else if (sel == 2) {
                          cout << "Please enter deposit amount: ";
                          cin >> amount;
                          my_checks.deposit (amount):
             }




           // checks
           else if (sel == 3) {
                     cout << "Please enter amount of check: ";
                     cin >> amount;
                     my_checks.check (amount);
           }
           // balance inquiry
           else if (sel == 4) {
                     cout << fixed << setprecision(2);
                     cout << "The balance is " <<
                                my_checks.query ( ) << endl;
           }
           // get next user choice
           sel = menu ( );
    } // end while
    return 0;
}




                                                                      10
Example 3
• Write a class Can that calculates the
  surface area, volume, and weight of a can
  surface area = 2p r(r+h)
  volume = p r2h
  weight (aluminum) = 0.1oz/in2 of surface
  area
  weight (steel) = 0.5 oz/in2 of surface




                        Class Can
class Can {
   private:
       float radius, height;
       char material; // S for steel, A for aluminum
   public:
       Can (float, float, char);
       float volume ( );
       float surface_area( );
       float weight ( );
};




                          Methods
// constructor has arguments
Can::Can(float r, float h, char m){
   radius = r;
   height = h;
   material = m;
}
float Can::volume( ) {
   return (3.14 * radius * radius * height);
}




                                                       11
Methods
float Can::surface_area ( ){
   return ( 2 * 3.14* radius * (radius + height));
}

float Can::weight ( ) {
   if (material == 'S')
        return ( 0.5 * surface_area( ));
   else
        return (0.1 * surface_area( ) );
}




                              Main
int main ( ) {
   Can popcan(1, 5, 'A');
   cout << "Aluminum popcan is about 5 inches high and 1
        inch in diameter." << endl;
   cout << "Volume is " << popcan.volume( ) << " cubic
        inches" << endl;
   cout << "Surface area is " << popcan.surface_area ( )
        <<" square inches" << endl;
   cout << "Weight is " << popcan.weight ( ) << " ounces"
        << endl;
   return 0;
}




                             Output
Aluminum popcan is about 5 inches high
  and 1 inch in diameter.
Volume is 15.7 cubic inches
Surface area is 37.68 square inches
Weight is 3.768 ounces




                                                            12
C++ has built-in classes
• Recall that to create an input file, use
// class definition in fstream
#include <fstream>
// class is ifstream, object is input_file
ifstream input_file;
//close is a method of ifstream
input_file.close ( );




                      String Class
#include <string> //class definition here
// class is string, object is my_name
string my_name;
// Can set the object directly
my_name = "Joan";
// methods
cout << my_name.length( );            //4
//substring of length 2 starting from character 0
cout << my_name.substr(0, 2);        //Jo




                                                    13

Más contenido relacionado

La actualidad más candente

Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelRamrao Desai
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?Kyle Oba
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsP3 InfoTech Solutions Pvt. Ltd.
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOMJalpesh Vasa
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IEduardo Bergavera
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindiappsdevelopment
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.Tarunsingh198
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++RAJ KUMAR
 

La actualidad más candente (20)

Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and Objects
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Swift Programming - Part 2
Swift Programming - Part 2Swift Programming - Part 2
Swift Programming - Part 2
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Python advance
Python advancePython advance
Python advance
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 
Objective-c Runtime
Objective-c RuntimeObjective-c Runtime
Objective-c Runtime
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 

Destacado (10)

computer science sample papers 1
computer science sample papers 1computer science sample papers 1
computer science sample papers 1
 
Boolean algebra
Boolean algebraBoolean algebra
Boolean algebra
 
Oop basic concepts
Oop basic conceptsOop basic concepts
Oop basic concepts
 
Physics
PhysicsPhysics
Physics
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
computer science sample papers 2
computer science sample papers 2computer science sample papers 2
computer science sample papers 2
 
Boolean algebra laws
Boolean algebra lawsBoolean algebra laws
Boolean algebra laws
 
computer science sample papers 3
computer science sample papers 3computer science sample papers 3
computer science sample papers 3
 
c++ program for Railway reservation
c++ program for Railway reservationc++ program for Railway reservation
c++ program for Railway reservation
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 

Similar a Class

00-intro-to-classes.pdf
00-intro-to-classes.pdf00-intro-to-classes.pdf
00-intro-to-classes.pdfTamiratDejene1
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfLadallaRajKumar
 
Procedure to create_the_calculator_application java
Procedure to create_the_calculator_application javaProcedure to create_the_calculator_application java
Procedure to create_the_calculator_application javagthe
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and DestructorsKeyur Vadodariya
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxAshrithaRokkam
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptxRassjb
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in javaagorolabs
 
While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...bhargavi804095
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4thConnex
 
Friend this-new&delete
Friend this-new&deleteFriend this-new&delete
Friend this-new&deleteShehzad Rizwan
 

Similar a Class (20)

Classes
ClassesClasses
Classes
 
00-intro-to-classes.pdf
00-intro-to-classes.pdf00-intro-to-classes.pdf
00-intro-to-classes.pdf
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Lecture02
Lecture02Lecture02
Lecture02
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
C#2
C#2C#2
C#2
 
Procedure to create_the_calculator_application java
Procedure to create_the_calculator_application javaProcedure to create_the_calculator_application java
Procedure to create_the_calculator_application java
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 
Constructor
ConstructorConstructor
Constructor
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 
While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...
 
11-Classes.ppt
11-Classes.ppt11-Classes.ppt
11-Classes.ppt
 
Constructor,destructors cpp
Constructor,destructors cppConstructor,destructors cpp
Constructor,destructors cpp
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Class and object C++.pptx
Class and object C++.pptxClass and object C++.pptx
Class and object C++.pptx
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
Friend this-new&delete
Friend this-new&deleteFriend this-new&delete
Friend this-new&delete
 

Más de Swarup Kumar Boro (16)

c++ program for Canteen management
c++ program for Canteen managementc++ program for Canteen management
c++ program for Canteen management
 
Pointers
PointersPointers
Pointers
 
File handling
File handlingFile handling
File handling
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Queue
QueueQueue
Queue
 
Stack
StackStack
Stack
 
Functions
FunctionsFunctions
Functions
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 
2-D array
2-D array2-D array
2-D array
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
Unit 3
Unit  3Unit  3
Unit 3
 
Computer science study material
Computer science study materialComputer science study material
Computer science study material
 
01 computer communication and networks v
01 computer communication and networks v01 computer communication and networks v
01 computer communication and networks v
 
1-D array
1-D array1-D array
1-D array
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Physics activity
Physics activityPhysics activity
Physics activity
 

Último

Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 

Último (20)

Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 

Class

  • 1. Classes and Objects in C++ Data Types • Recall that C++ has predefined data types, such as int • int x; // Creates a specific instance of an // integer named x • C++ also predefines operations that can be used on integers, such as + and * Classes • Sometimes, a programmer will want to define a custom "thing" and the operations that can be performed on that "thing" • A class is the definition • An object is a particular instance of a class • Classes contain – data, called members – functions, called methods 1
  • 2. Class Declaration class Class_name { public: member (data) definitions method (function) definitions private: member (data) definitions method (function) definitions }; // order of public and private can be reversed // data is seldom public // note semicolon after } Public and Private • Public members and methods can be accessed from outside the class and provide the interface • Private members and methods cannot be accessed from outside the class Data Hiding • Recall that many programmers can each write a small piece of a large program • Need to have some way to define how other programmers can use your stuff – Public methods are the only way for any other code to access the class • Need to have some way to keep other programmers from messing up your stuff – Private methods and members cannot be accessed from outside the class 2
  • 3. Reusability and Changeability • Writing programs is expensive, so organizations try to reuse code and avoid changing it • If classes are well written, they can be reused in several programs • Also, the internals of a class can be rewritten - as long as the interface does not change, programs that use that class do not need to be changed Example 1 Create a counter. Other parts of the program should be able to increment the counter and read the counter class Counter { public: // constructor to initialize the object - note no function type Counter ( ) { currentcount = 0; }; // increment the counter void count( ) { currentcount++; }; // get the current value of the counter int readcounter( ) { return currentcount; }; private: int currentcount; }; 3
  • 4. Constructors • Constructors are methods that initialize an object – Must have same name as the class – Declaration is odd - no function type Counter ( ) { ..... } – Not required, but should be used when data needs to be initialized – Never explicitly called - automatically called when an object of this class is declared Destructors • Destructors are methods that clean up when an object is destroyed – Must have the same name as the class, but with a ~ in front – No function type in declaration ~ Counter ( ) { ..... } – Also not required, but should be provided if necessary to release memory, for example – Never explicitly called - automatically called when an object of this class is destroyed Creating an Object • To create an instance of class counter (called an object) declare it as you would any other variable Class_name object_name(s); – This automatically calls the constructor method to initialize the object Counter my_counter; 4
  • 5. Using an Object • Using a public method is similar to a function call object_name.method_name (arguments) my_counter.count( ); int current = my_counter.readcounter( ); Using an Object • Common error - using the class name instead of the object name Counter.count ( ); // WRONG! my_counter.count ( ); // RIGHT! • Common error - trying to use private members or methods outside the class cout << currentcount ; // WRONG! cout << my_counter.readcounter ( ); // RIGHT! Putting It All Together #include <iostream> using namespace std; 5
  • 6. class Counter { public: // constructor to initialize the object Counter ( ) { currentcount = 0; }; // increment the counter void count( ) { currentcount++; }; // get the current value of the counter int readcounter( ) { return currentcount; }; private: int currentcount; }; int main ( ) { // declare two objects Counter first_counter, second_counter; // increment counters first_counter.count( ); second_counter.count( ); second_counter.count( ); //display counts cout << "first counter is " << first_counter.readcounter( ) << endl; cout << "second counter is " << second_counter.readcounter( ) << endl; return 0; } Output first counter is 1 second counter is 2 6
  • 7. Global Scope • Anything declared outside of a function, such as the class in this example or a variable, can be used by any function in the program and is global • Anything declared inside a function can only be used in that function • Usual to declare classes to be global • Global variables are bad programming practice and should be avoided Function Prototypes in Class Declarations • In the previous example, the functions (methods) were completely declared within the class declaration • Often more readable to put only function prototypes in the class declaration and put the method implementations later • use class_name::method_name when declaring the methods • This is the usual convention class Counter { Counter::Counter ( ) { public: currentcount = 0; } Counter ( ); void count( ); void Counter::count ( ){ int readcounter( ); currentcount ++; private: } int currentcount; int Counter::readcounter ( ){ } return currentcount ; } 7
  • 8. Identifying Classes • Often, it is not immediately obvious what the classes should be to solve a particular problem • One hint is to consider some of the nouns in the problem statement to be the classes. The verbs in the problem statement will then be the methods. Example 2 • Write a program that manages a checkbook. The user should be able to set the original account balance, deposit money in the account, remove money when a check is written, and query the current balance. Example 2 class CheckBook public methods are init, deposit, check, and query Pseudocode for main program display menu and get user choice while user does not choose quit Set starting balance: get the amount, call init Deposit: get amount, call deposit Write a check: get amount, call check Balance: call query, display balance display menu and get user choice 8
  • 9. Example 2 Program #include <iostream> #include <iomanip> using namespace std; Class Declaration class CheckBook{ private: float balance; public: CheckBook ( ); //constructor void init (float); // set balance void deposit (float); //add deposit void check (float); //subtract check float query ( ); //get balance }; Class Method Declarations CheckBook::CheckBook ( ) { balance = 0; } void CheckBook::init (float money) { balance = money; } void CheckBook::deposit (float money) { balance = balance + money; } void CheckBook:: check (float money){ balance = balance - money; } float CheckBook:: query ( ){ return balance; } 9
  • 10. Menu Function int menu ( ) { int choice; cout << "0: Quit" << endl; cout << "1: Set initial balance" << endl; cout << "2: Deposit" << endl; cout << "3: Deduct a check" << endl; cout << "4: Find current balance" << endl; cout << "Please enter your selection: "; cin >> choice; return choice; } int main ( ) { int sel = menu ( ); // get initial user input float amount; CheckBook my_checks; // declare object // loop until user enters 0 to quit while (sel != 0) { // set initial balance if (sel == 1) { cout << "Please enter initial balance: "; cin >> amount; my_checks.init(amount ); } // deposit else if (sel == 2) { cout << "Please enter deposit amount: "; cin >> amount; my_checks.deposit (amount): } // checks else if (sel == 3) { cout << "Please enter amount of check: "; cin >> amount; my_checks.check (amount); } // balance inquiry else if (sel == 4) { cout << fixed << setprecision(2); cout << "The balance is " << my_checks.query ( ) << endl; } // get next user choice sel = menu ( ); } // end while return 0; } 10
  • 11. Example 3 • Write a class Can that calculates the surface area, volume, and weight of a can surface area = 2p r(r+h) volume = p r2h weight (aluminum) = 0.1oz/in2 of surface area weight (steel) = 0.5 oz/in2 of surface Class Can class Can { private: float radius, height; char material; // S for steel, A for aluminum public: Can (float, float, char); float volume ( ); float surface_area( ); float weight ( ); }; Methods // constructor has arguments Can::Can(float r, float h, char m){ radius = r; height = h; material = m; } float Can::volume( ) { return (3.14 * radius * radius * height); } 11
  • 12. Methods float Can::surface_area ( ){ return ( 2 * 3.14* radius * (radius + height)); } float Can::weight ( ) { if (material == 'S') return ( 0.5 * surface_area( )); else return (0.1 * surface_area( ) ); } Main int main ( ) { Can popcan(1, 5, 'A'); cout << "Aluminum popcan is about 5 inches high and 1 inch in diameter." << endl; cout << "Volume is " << popcan.volume( ) << " cubic inches" << endl; cout << "Surface area is " << popcan.surface_area ( ) <<" square inches" << endl; cout << "Weight is " << popcan.weight ( ) << " ounces" << endl; return 0; } Output Aluminum popcan is about 5 inches high and 1 inch in diameter. Volume is 15.7 cubic inches Surface area is 37.68 square inches Weight is 3.768 ounces 12
  • 13. C++ has built-in classes • Recall that to create an input file, use // class definition in fstream #include <fstream> // class is ifstream, object is input_file ifstream input_file; //close is a method of ifstream input_file.close ( ); String Class #include <string> //class definition here // class is string, object is my_name string my_name; // Can set the object directly my_name = "Joan"; // methods cout << my_name.length( ); //4 //substring of length 2 starting from character 0 cout << my_name.substr(0, 2); //Jo 13