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

More Related Content

PPT
Templates exception handling
ODP
(7) c sharp introduction_advanvced_features_part_ii
PPTX
C sharp part 001
PDF
Container Classes
PPTX
PDF
The Ring programming language version 1.8 book - Part 86 of 202
PDF
2java Oop
Templates exception handling
(7) c sharp introduction_advanvced_features_part_ii
C sharp part 001
Container Classes
The Ring programming language version 1.8 book - Part 86 of 202
2java Oop

What's hot (18)

PPT
Delegate
PDF
Lecture 5: Functional Programming
PPTX
Compile time polymorphism
ZIP
PPTX
Templates
DOCX
D404 ex-4-2
PPTX
Introduction to c_plus_plus (6)
PPT
C++ classes tutorials
PDF
Java patterns in Scala
ZIP
PDF
Semmle Codeql
PPT
Java: Class Design Examples
PPT
Unit iii
PDF
麻省理工C++公开教学课程(二)
PDF
Functor, Apply, Applicative And Monad
PPT
C# Variables and Operators
PPT
Java 8 Streams
PDF
TI1220 Lecture 6: First-class Functions
Delegate
Lecture 5: Functional Programming
Compile time polymorphism
Templates
D404 ex-4-2
Introduction to c_plus_plus (6)
C++ classes tutorials
Java patterns in Scala
Semmle Codeql
Java: Class Design Examples
Unit iii
麻省理工C++公开教学课程(二)
Functor, Apply, Applicative And Monad
C# Variables and Operators
Java 8 Streams
TI1220 Lecture 6: First-class Functions
Ad

Viewers also liked (19)

PDF
Pointers
PDF
Structures in c++
PDF
Boolean
PDF
C++ revision tour
PDF
Constructor & destructor
PPTX
Spider Man Takes A Day Off
TXT
Railway reservation
PPTX
Hoax Chris Regan
PPTX
Hoax Chris Regan
TXT
Program to sort array using insertion sort
PDF
Implementation of oop concept in c++
PDF
Functions
PDF
EPSON PROJECTOR EB X14
DOCX
resume_varun_sfdc
PPTX
Mi contexto de formación SENA
PPTX
Romanesque art
PPTX
Presentation_NEW.PPTX
PDF
Custom Company Stores
DOCX
Major events of 2013
Pointers
Structures in c++
Boolean
C++ revision tour
Constructor & destructor
Spider Man Takes A Day Off
Railway reservation
Hoax Chris Regan
Hoax Chris Regan
Program to sort array using insertion sort
Implementation of oop concept in c++
Functions
EPSON PROJECTOR EB X14
resume_varun_sfdc
Mi contexto de formación SENA
Romanesque art
Presentation_NEW.PPTX
Custom Company Stores
Major events of 2013
Ad

Similar to Classes (20)

PPT
c++ lecture 1
PPT
c++ lecture 1
PPT
c++ introduction
PDF
Object Oriented Programming (OOP) using C++ - Lecture 3
PPTX
Object Oriented Programming using C++: Ch06 Objects and Classes.pptx
PPTX
Chapter 2 OOP using C++ (Introduction).pptx
PPT
oop objects_classes
PPTX
Class and object
PPT
While writing program in any language, you need to use various variables to s...
PPT
11-Classes.ppt
PPTX
Oop objects_classes
PPTX
oopusingc.pptx
PPT
classandobjectunit2-150824133722-lva1-app6891.ppt
PPTX
C++ language
PPT
Bca 2nd sem u-2 classes & objects
PDF
classes and objects.pdfggggggggffffffffgggf
PPTX
05 Object Oriented Concept Presentation.pptx
PPT
Mca 2nd sem u-2 classes & objects
DOCX
OOP and C++Classes
c++ lecture 1
c++ lecture 1
c++ introduction
Object Oriented Programming (OOP) using C++ - Lecture 3
Object Oriented Programming using C++: Ch06 Objects and Classes.pptx
Chapter 2 OOP using C++ (Introduction).pptx
oop objects_classes
Class and object
While writing program in any language, you need to use various variables to s...
11-Classes.ppt
Oop objects_classes
oopusingc.pptx
classandobjectunit2-150824133722-lva1-app6891.ppt
C++ language
Bca 2nd sem u-2 classes & objects
classes and objects.pdfggggggggffffffffgggf
05 Object Oriented Concept Presentation.pptx
Mca 2nd sem u-2 classes & objects
OOP and C++Classes

More from Swarup Boro (16)

DOCX
Concatenation of two strings using class in c++
DOCX
Program: Inheritance in Class - to find topper out of 10 students
DOCX
Array using recursion
DOCX
Binary addition using class concept in c++
DOCX
Study of Diffusion of solids in Liquids
TXT
Program using function overloading
TXT
Program to find the avg of two numbers
TXT
Program to find factorial of a number
TXT
Canteen management program
TXT
C++ program using class
PDF
Arrays and library functions
PDF
PDF
PDF
Computer communication and networks
PDF
2D Array
PDF
1D Array
Concatenation of two strings using class in c++
Program: Inheritance in Class - to find topper out of 10 students
Array using recursion
Binary addition using class concept in c++
Study of Diffusion of solids in Liquids
Program using function overloading
Program to find the avg of two numbers
Program to find factorial of a number
Canteen management program
C++ program using class
Arrays and library functions
Computer communication and networks
2D Array
1D Array

Recently uploaded (20)

PPTX
Unit 4 Computer Architecture Multicore Processor.pptx
PDF
Empowerment Technology for Senior High School Guide
PPTX
What’s under the hood: Parsing standardized learning content for AI
PPTX
B.Sc. DS Unit 2 Software Engineering.pptx
DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PDF
HVAC Specification 2024 according to central public works department
PDF
International_Financial_Reporting_Standa.pdf
PDF
advance database management system book.pdf
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PDF
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 1).pdf
PDF
Uderstanding digital marketing and marketing stratergie for engaging the digi...
PDF
Complications of Minimal Access-Surgery.pdf
PPTX
Education and Perspectives of Education.pptx
PDF
LIFE & LIVING TRILOGY - PART - (2) THE PURPOSE OF LIFE.pdf
PDF
Mucosal Drug Delivery system_NDDS_BPHARMACY__SEM VII_PCI.pdf
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
LIFE & LIVING TRILOGY - PART (3) REALITY & MYSTERY.pdf
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PDF
Journal of Dental Science - UDMY (2021).pdf
PPTX
Core Concepts of Personalized Learning and Virtual Learning Environments
Unit 4 Computer Architecture Multicore Processor.pptx
Empowerment Technology for Senior High School Guide
What’s under the hood: Parsing standardized learning content for AI
B.Sc. DS Unit 2 Software Engineering.pptx
Cambridge-Practice-Tests-for-IELTS-12.docx
HVAC Specification 2024 according to central public works department
International_Financial_Reporting_Standa.pdf
advance database management system book.pdf
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 1).pdf
Uderstanding digital marketing and marketing stratergie for engaging the digi...
Complications of Minimal Access-Surgery.pdf
Education and Perspectives of Education.pptx
LIFE & LIVING TRILOGY - PART - (2) THE PURPOSE OF LIFE.pdf
Mucosal Drug Delivery system_NDDS_BPHARMACY__SEM VII_PCI.pdf
A powerpoint presentation on the Revised K-10 Science Shaping Paper
LIFE & LIVING TRILOGY - PART (3) REALITY & MYSTERY.pdf
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
Journal of Dental Science - UDMY (2021).pdf
Core Concepts of Personalized Learning and Virtual Learning Environments

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