SlideShare une entreprise Scribd logo
1  sur  13
Télécharger pour lire hors ligne
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 {
public:
Counter ( );
void count( );
int readcounter( );
private:
int currentcount;
}

Counter::Counter ( ) {
currentcount = 0;
}
void Counter::count ( ){
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 ( );
void init (float);
void deposit (float);
void check (float);
float query ( );
};

//constructor
// set balance
//add deposit
//subtract check
//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

Contenu connexe

Tendances

Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Sayed Ahmed
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsMayank Jain
 
Java patterns in Scala
Java patterns in ScalaJava patterns in Scala
Java patterns in ScalaRadim Pavlicek
 
Semmle Codeql
Semmle Codeql Semmle Codeql
Semmle Codeql M. S.
 
Java: Class Design Examples
Java: Class Design ExamplesJava: Class Design Examples
Java: Class Design ExamplesTareq Hasan
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)ProCharm
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadOliver Daff
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and OperatorsSunil OS
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 

Tendances (18)

Delegate
DelegateDelegate
Delegate
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
Compile time polymorphism
Compile time polymorphismCompile time polymorphism
Compile time polymorphism
 
Day 1
Day 1Day 1
Day 1
 
Templates
TemplatesTemplates
Templates
 
D404 ex-4-2
D404 ex-4-2D404 ex-4-2
D404 ex-4-2
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Java patterns in Scala
Java patterns in ScalaJava patterns in Scala
Java patterns in Scala
 
Day 2
Day 2Day 2
Day 2
 
Semmle Codeql
Semmle Codeql Semmle Codeql
Semmle Codeql
 
Java: Class Design Examples
Java: Class Design ExamplesJava: Class Design Examples
Java: Class Design Examples
 
Unit iii
Unit iiiUnit iii
Unit iii
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 

En vedette

Structures in c++
Structures in c++Structures in c++
Structures in c++Swarup Boro
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tourSwarup Boro
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructorSwarup Boro
 
Spider Man Takes A Day Off
Spider Man Takes A Day OffSpider Man Takes A Day Off
Spider Man Takes A Day Offchrisregan501
 
Railway reservation
Railway reservationRailway reservation
Railway reservationSwarup Boro
 
Program to sort array using insertion sort
Program to sort array using insertion sortProgram to sort array using insertion sort
Program to sort array using insertion sortSwarup Boro
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++Swarup Boro
 
resume_varun_sfdc
resume_varun_sfdcresume_varun_sfdc
resume_varun_sfdcVarun Singh
 
Mi contexto de formación SENA
Mi contexto de formación SENAMi contexto de formación SENA
Mi contexto de formación SENAadiela3458
 
Major events of 2013
Major events of 2013Major events of 2013
Major events of 2013champchild
 

En vedette (19)

Pointers
PointersPointers
Pointers
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Boolean
BooleanBoolean
Boolean
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Spider Man Takes A Day Off
Spider Man Takes A Day OffSpider Man Takes A Day Off
Spider Man Takes A Day Off
 
Railway reservation
Railway reservationRailway reservation
Railway reservation
 
Hoax Chris Regan
Hoax Chris ReganHoax Chris Regan
Hoax Chris Regan
 
Hoax Chris Regan
Hoax Chris ReganHoax Chris Regan
Hoax Chris Regan
 
Program to sort array using insertion sort
Program to sort array using insertion sortProgram to sort array using insertion sort
Program to sort array using insertion sort
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 
Functions
FunctionsFunctions
Functions
 
EPSON PROJECTOR EB X14
EPSON PROJECTOR EB X14EPSON PROJECTOR EB X14
EPSON PROJECTOR EB X14
 
resume_varun_sfdc
resume_varun_sfdcresume_varun_sfdc
resume_varun_sfdc
 
Mi contexto de formación SENA
Mi contexto de formación SENAMi contexto de formación SENA
Mi contexto de formación SENA
 
Romanesque art
Romanesque artRomanesque art
Romanesque art
 
Presentation_NEW.PPTX
Presentation_NEW.PPTXPresentation_NEW.PPTX
Presentation_NEW.PPTX
 
Custom Company Stores
Custom Company StoresCustom Company Stores
Custom Company Stores
 
Major events of 2013
Major events of 2013Major events of 2013
Major events of 2013
 

Similaire à Classes

Similaire à Classes (20)

Class
ClassClass
Class
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
00-intro-to-classes.pdf
00-intro-to-classes.pdf00-intro-to-classes.pdf
00-intro-to-classes.pdf
 
Friend this-new&delete
Friend this-new&deleteFriend this-new&delete
Friend this-new&delete
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
C++ theory
C++ theoryC++ theory
C++ theory
 
UNIT3 on object oriented programming.pptx
UNIT3 on object oriented programming.pptxUNIT3 on object oriented programming.pptx
UNIT3 on object oriented programming.pptx
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
C++ process new
C++ process newC++ process new
C++ process new
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptx
 
Constructor
ConstructorConstructor
Constructor
 
Constructor,destructors cpp
Constructor,destructors cppConstructor,destructors cpp
Constructor,destructors cpp
 
What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
 
Unit ii
Unit iiUnit ii
Unit ii
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.ppt
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 

Plus de Swarup Boro

Concatenation of two strings using class in c++
Concatenation of two strings using class in c++Concatenation of two strings using class in c++
Concatenation of two strings using class in c++Swarup Boro
 
Program: Inheritance in Class - to find topper out of 10 students
Program: Inheritance in Class - to find topper out of 10 studentsProgram: Inheritance in Class - to find topper out of 10 students
Program: Inheritance in Class - to find topper out of 10 studentsSwarup Boro
 
Array using recursion
Array using recursionArray using recursion
Array using recursionSwarup Boro
 
Binary addition using class concept in c++
Binary addition using class concept in c++Binary addition using class concept in c++
Binary addition using class concept in c++Swarup Boro
 
Study of Diffusion of solids in Liquids
Study of Diffusion of solids in Liquids                                 Study of Diffusion of solids in Liquids
Study of Diffusion of solids in Liquids Swarup Boro
 
Program using function overloading
Program using function overloadingProgram using function overloading
Program using function overloadingSwarup Boro
 
Program to find the avg of two numbers
Program to find the avg of two numbersProgram to find the avg of two numbers
Program to find the avg of two numbersSwarup Boro
 
Program to find factorial of a number
Program to find factorial of a numberProgram to find factorial of a number
Program to find factorial of a numberSwarup Boro
 
Canteen management program
Canteen management programCanteen management program
Canteen management programSwarup Boro
 
C++ program using class
C++ program using classC++ program using class
C++ program using classSwarup Boro
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functionsSwarup Boro
 
Computer communication and networks
Computer communication and networks Computer communication and networks
Computer communication and networks Swarup Boro
 

Plus de Swarup Boro (16)

Concatenation of two strings using class in c++
Concatenation of two strings using class in c++Concatenation of two strings using class in c++
Concatenation of two strings using class in c++
 
Program: Inheritance in Class - to find topper out of 10 students
Program: Inheritance in Class - to find topper out of 10 studentsProgram: Inheritance in Class - to find topper out of 10 students
Program: Inheritance in Class - to find topper out of 10 students
 
Array using recursion
Array using recursionArray using recursion
Array using recursion
 
Binary addition using class concept in c++
Binary addition using class concept in c++Binary addition using class concept in c++
Binary addition using class concept in c++
 
Study of Diffusion of solids in Liquids
Study of Diffusion of solids in Liquids                                 Study of Diffusion of solids in Liquids
Study of Diffusion of solids in Liquids
 
Program using function overloading
Program using function overloadingProgram using function overloading
Program using function overloading
 
Program to find the avg of two numbers
Program to find the avg of two numbersProgram to find the avg of two numbers
Program to find the avg of two numbers
 
Program to find factorial of a number
Program to find factorial of a numberProgram to find factorial of a number
Program to find factorial of a number
 
Canteen management program
Canteen management programCanteen management program
Canteen management program
 
C++ program using class
C++ program using classC++ program using class
C++ program using class
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Queue
QueueQueue
Queue
 
Stack
StackStack
Stack
 
Computer communication and networks
Computer communication and networks Computer communication and networks
Computer communication and networks
 
2D Array
2D Array2D Array
2D Array
 
1D Array
1D Array1D Array
1D Array
 

Dernier

MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 

Dernier (20)

MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 

Classes

  • 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 { public: Counter ( ); void count( ); int readcounter( ); private: int currentcount; } Counter::Counter ( ) { currentcount = 0; } void Counter::count ( ){ 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 ( ); void init (float); void deposit (float); void check (float); float query ( ); }; //constructor // set balance //add deposit //subtract check //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