SlideShare uma empresa Scribd logo
1 de 31
Objects and Classes
Objectives
 To understand objects and classes, and the use of classes to
model objects
 To learn how to declare a class and how to create an object of
a class
 To understand the role of constructors when creating objects
 To learn constructor overloading
 To understand the scope of data fields (access modifiers),
encapsulation
 To reference hidden data field using the this pointer
Object-oriented Programming (OOP)
 Object-oriented programming approach organizes
programs in a way that mirrors the real world, in
which all objects are associated with both attributes
and behaviors
 Object-oriented programming involves thinking in
terms of objects
 An OOP program can be viewed as a collection of
cooperating objects
OO Programming Concepts
 Classes and objects are the two main aspects of object
oriented programming.
 A class is an abstraction or a template that creates a new
type whereas objects are instances of the class.
 An object represents an entity in the real world that can
be distinctly identified. For example, a student, a desk, a
circle, a button, and even a loan can all be viewed as
objects.
Classes in OOP
 Classes are constructs/templates that define
objects of the same type.
 A class uses variables to define data fields and
functions to define behaviors.
 Additionally, a class provides a special type of
function, known as constructors, which are invoked
to construct objects from the class.
Objects in OOP
 An object has a unique identity, state, and behaviors.
 The state of an object consists of a set of data fields (also
known as properties) with their current values.
 The behavior of an object is defined by a set of functions
Class and Object
 A class is template that defines what an object’s
data and function will be. A C++ class uses
variables to define data fields, and functions to
define behavior.
 An object is an instance of a class (the terms
object and instance are often interchangeable).
UML Diagram for Class and Object
Circle
radius: double
Circle()
Circle(newRadius: double)
getArea(): double
circle1: Circle
radius: 10
Class name
Data fields
Constructors and Methods
circle2: Circle
radius: 25
circle3: Circle
radius: 125
Class in C++ - Example
Class in C++ - Example
class Circle
{
public:
// The radius of this circle
double radius;
// Construct a circle object
Circle()
{
radius = 1;
}
// Construct a circle object
Circle(double newRadius)
{
radius = newRadius;
}
// Return the area of this circle
double getArea()
{
return radius * radius * 3.14159;
}
};
Data field
Function
Constructors
Class is a Type
 You can use primitive data types to define
variables.
 You can also use class names to declare object
names. In this sense, a class is an abstract type,
data type or user-defined data type.
Class Data Members and Member Functions
 The data items within a class are
called data members or data
fields or instance variables
 Member functions are functions
that are included within a class.
Also known as instance
functions.
Object Creation - Instantiation
 In C++, you can assign a name when creating an object.
 A constructor is invoked when an object is created.
 The syntax to create an object using the no-arg
constructor is
ClassName objectName;
 Defining objects in this way means creating them. This is
also called instantiating them.
A Simple Program – Object Creation
class Circle
{
private:
double radius;
public:
Circle()
{ radius = 5.0; }
double getArea()
{ return radius * radius * 3.14159; }
};
Object InstanceC1
: C1
radius: 5.0
void main()
{
Circle C1;
//C1.radius = 10; can’t access private member outside the class
cout<<“Area of circle = “<<C1.getArea();
}
Allocate memory
for radius
Constructors
 In object-oriented programming, a constructor in a class is a
special function used to create an object. Constructor has
exactly the same name as the defining class
 Constructors can be overloaded (i.e., multiple constructors
with different signatures), making it easy to construct objects
with different initial data values.
 A class may be declared without constructors. In this case, a
no-argument constructor with an empty body is implicitly
declared in the class known as default constructor
 Note: Default constructor is provided automatically only if no
constructors are explicitly declared in the class.
Constructors’ Properties
 Constructors must have the same name as the class
itself.
 Constructors do not have a return type—not even void.
 Constructors play the role of initializing objects.
Object Member Access Operator
 After object creation, its data and functions can be
accessed (invoked) using the (.) operator, also known
as the object member access operator.
 objectName.dataField references a data field in the
object
 objectName.function() invokes a function on the
object
A Simple Program – Accessing Members
class Circle
{
private:
double radius;
public:
Circle()
{ radius = 5.0; }
double getArea()
{ return radius * radius * 3.14159; }
};
Object InstanceC1
: C1
radius: 5.0
void main()
{
Circle C1;
//C1.radius = 10; can’t access private member outside the class
cout<<“Area of circle = “<<C1.getArea();
}
Allocate memory
for radius
Access Modifiers
 Access modifiers are used to set access levels
for classes, variables, methods and constructors
 private, public, and protected
 In C++, default accessibility is private
Data Hiding - Data Field Encapsulation
 A key feature of OOP is data hiding, which means that
data is concealed within a class so that it cannot be
accessed mistakenly by functions outside the class.
 To prevent direct modification of class attributes
(outside the class), the primary mechanism for hiding
data is to put it in a class and make it private using
private keyword. This is known as data field
encapsulation.
Hidden from Whom?
 Data hiding means hiding data from parts of the
program that don’t need to access it. More
specifically, one class’s data is hidden from other
classes.
 Data hiding is designed to protect well-intentioned
programmers from mistakes.
A Simple Program – Accessing Member Function
class Circle
{
private:
double radius;
public:
Circle()
{ radius = 5.0; }
double getArea()
{ return radius * radius * 3.14159; }
};
Object InstanceC1
: C1
radius: 5.0
void main()
{
Circle C1;
//C1.radius = 10; can’t access private member outside the class
cout<<“Area of circle = “<<C1.getArea();
}
Allocate memory
for radius
A Simple Program – Default Constructor
class Circle
{
private:
double radius;
public:
double getArea()
{ return radius * radius * 3.14159; }
};
// No Constructor Here
Object InstanceC1
void main()
{
Circle C1;
//C1.radius = 10; can’t access private member outside the class
cout<<“Area of circle = “<<C1.getArea();
}
//Default Constructor
Circle()
{ }
: C1
radius: Any Value
Allocate memory
for radius
Object Construction with Arguments
 The syntax to declare an object using a constructor with
arguments is
ClassName objectName(arguments);
 For example, the following declaration creates an object
named circle1 by invoking the Circle class’s constructor
with a specified radius 5.5.
Circle circle1(5.5);
A Simple Program – Constructor with Arguments
class Circle
{
private:
double radius;
public:
Circle(double rad)
{ radius = rad; }
double getArea()
{ return radius * radius * 3.14159; }
};
Object InstanceC1
: C1
radius: 9.0
void main()
{
Circle C1(9.0);
//C1.radius = 10; can’t access private member outside the class
cout<<“Area of circle = “<<C1.getArea();
}
Allocate memory
for radius
Output of the following Program?
class Circle
{
private:
double radius;
public:
Circle(double rad)
{ radius = rad; }
double getArea()
{ return radius * radius * 3.14159; }
};
void main()
{
Circle C1;
cout<<“Area of circle = “<<C1.getArea();
}
Constructor Overloading
class Circle
{
private:
double radius;
public:
Circle ()
{ radius = 1; }
Circle(double rad)
{ radius = rad; }
double getArea()
{ return radius * radius * 3.14159; }
};
void main()
{
Circle C2(8.0);
Circle C1;
cout<<“Area of circle = “<<C1.getArea();
}
The this Pointer
class Circle
{
private:
double radius;
public:
Circle(double radius)
{ this->radius = radius; }
double getArea()
{ return radius * radius * 3.14159; }
};
void main()
{
Circle C1(99.0);
cout<<“Area of circle = “<<C1.getArea();
}
The this Pointer
 this is keyword, which is a special built-in pointer that
references to the calling object.
 The this pointer is passed as a hidden argument to all
nonstatic member function calls and is available as a
local variable within the body of all nonstatic functions.
 Can be used to access instance variables within
constructors and member functions
Exercise
Design a class named Account that contains:
 A private int data field named id for the account (default 0)
 A private double data field balance for the account (default 0)
 A private double data field named annualInterestRate that stores
the current interest rate (default 0).
 A no-arg constructor that creates a default account.
 A constructor that creates an account with the specified id, initial
balance, and annual interest rate.
 A function named getAnnualInterestRate() that returns the annual
interest rate.
 A function named withdraw that withdraws a specified amount
from the account.
 A function named deposit that deposits a specified amount to the
account.
 A function named show to print all attribute values
 Implement the class. Write a test program that creates an Account
object with an account ID of 1122, a balance of $20,000, and an
annual interest rate of 4.5%. Use the withdraw method to
withdraw $2,500, use the deposit method to deposit $3,000, and
print the balance, the Annual interest, and the date when this
account was created.
 (Algebra: quadratic equations) Design a class named QuadraticEquation
for a quadratic equation. The class contains:
 Private data fields a, b, and c that represents three coefficients.
 A constructor for the arguments of a, b, and c.
 A function named getDiscriminant() that returns the discriminant, which
is b2 – 4ac
 The functions named getRoot1() and getRoot2() for returning two roots
of the equation
 Implement the class. Write a test program that prompts the user to
enter values for a, b, and c and displays the result based on the
discriminant. If the discriminant is positive, display the two roots. If the
discriminant is 0, display the one root. Otherwise, display “The equation
has no roots”.
Exercise

Mais conteúdo relacionado

Mais procurados (20)

Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
 
Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
 
Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
 
Kotlin
KotlinKotlin
Kotlin
 
Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
Java programs
Java programsJava programs
Java programs
 
Interface
InterfaceInterface
Interface
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Java programs
Java programsJava programs
Java programs
 
Core java
Core javaCore java
Core java
 
Operators
OperatorsOperators
Operators
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 

Destaque

SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummaryAmal Khailtash
 
Progressive Migration From 'e' to SystemVerilog: Case Study
Progressive Migration From 'e' to SystemVerilog: Case StudyProgressive Migration From 'e' to SystemVerilog: Case Study
Progressive Migration From 'e' to SystemVerilog: Case StudyDVClub
 
Coverage Solutions on Emulators
Coverage Solutions on EmulatorsCoverage Solutions on Emulators
Coverage Solutions on EmulatorsDVClub
 
Oop concepts classes_objects
Oop concepts classes_objectsOop concepts classes_objects
Oop concepts classes_objectsWilliam Olivier
 
Meta-Classes in Python
Meta-Classes in PythonMeta-Classes in Python
Meta-Classes in PythonGuy Wiener
 
L15 timers-counters-in-atmega328 p
L15 timers-counters-in-atmega328 pL15 timers-counters-in-atmega328 p
L15 timers-counters-in-atmega328 prsamurti
 

Destaque (6)

SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Progressive Migration From 'e' to SystemVerilog: Case Study
Progressive Migration From 'e' to SystemVerilog: Case StudyProgressive Migration From 'e' to SystemVerilog: Case Study
Progressive Migration From 'e' to SystemVerilog: Case Study
 
Coverage Solutions on Emulators
Coverage Solutions on EmulatorsCoverage Solutions on Emulators
Coverage Solutions on Emulators
 
Oop concepts classes_objects
Oop concepts classes_objectsOop concepts classes_objects
Oop concepts classes_objects
 
Meta-Classes in Python
Meta-Classes in PythonMeta-Classes in Python
Meta-Classes in Python
 
L15 timers-counters-in-atmega328 p
L15 timers-counters-in-atmega328 pL15 timers-counters-in-atmega328 p
L15 timers-counters-in-atmega328 p
 

Semelhante a Oop objects_classes

C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsMayank Jain
 
C++ Classes Tutorials.ppt
C++ Classes Tutorials.pptC++ Classes Tutorials.ppt
C++ Classes Tutorials.pptaasuran
 
Oops concept in c#
Oops concept in c#Oops concept in c#
Oops concept in c#ANURAG SINGH
 
Chapter22 static-class-member-example
Chapter22 static-class-member-exampleChapter22 static-class-member-example
Chapter22 static-class-member-exampleDeepak Singh
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsFALLEE31188
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and objectFajar Baskoro
 
Class and Object.ppt
Class and Object.pptClass and Object.ppt
Class and Object.pptGenta Sahuri
 
Class and Object.pptx
Class and Object.pptxClass and Object.pptx
Class and Object.pptxHailsh
 
Object and class presentation
Object and class presentationObject and class presentation
Object and class presentationnafisa rahman
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsRai University
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objectsRai University
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methodsfarhan amjad
 

Semelhante a Oop objects_classes (20)

C++ classes
C++ classesC++ classes
C++ classes
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C++ Classes Tutorials.ppt
C++ Classes Tutorials.pptC++ Classes Tutorials.ppt
C++ Classes Tutorials.ppt
 
Object & classes
Object & classes Object & classes
Object & classes
 
Oops concept in c#
Oops concept in c#Oops concept in c#
Oops concept in c#
 
Chapter22 static-class-member-example
Chapter22 static-class-member-exampleChapter22 static-class-member-example
Chapter22 static-class-member-example
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
 
UNIT I (1).ppt
UNIT I (1).pptUNIT I (1).ppt
UNIT I (1).ppt
 
UNIT I (1).ppt
UNIT I (1).pptUNIT I (1).ppt
UNIT I (1).ppt
 
Class and Object.ppt
Class and Object.pptClass and Object.ppt
Class and Object.ppt
 
Module 3 Class and Object.ppt
Module 3 Class and Object.pptModule 3 Class and Object.ppt
Module 3 Class and Object.ppt
 
Class and Object.pptx
Class and Object.pptxClass and Object.pptx
Class and Object.pptx
 
Oops concept
Oops conceptOops concept
Oops concept
 
C++ classes
C++ classesC++ classes
C++ classes
 
Object and class presentation
Object and class presentationObject and class presentation
Object and class presentation
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
 

Último

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
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
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
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
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
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 

Último (20)

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...
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
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
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
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
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
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
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 

Oop objects_classes

  • 2. Objectives  To understand objects and classes, and the use of classes to model objects  To learn how to declare a class and how to create an object of a class  To understand the role of constructors when creating objects  To learn constructor overloading  To understand the scope of data fields (access modifiers), encapsulation  To reference hidden data field using the this pointer
  • 3. Object-oriented Programming (OOP)  Object-oriented programming approach organizes programs in a way that mirrors the real world, in which all objects are associated with both attributes and behaviors  Object-oriented programming involves thinking in terms of objects  An OOP program can be viewed as a collection of cooperating objects
  • 4. OO Programming Concepts  Classes and objects are the two main aspects of object oriented programming.  A class is an abstraction or a template that creates a new type whereas objects are instances of the class.  An object represents an entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects.
  • 5. Classes in OOP  Classes are constructs/templates that define objects of the same type.  A class uses variables to define data fields and functions to define behaviors.  Additionally, a class provides a special type of function, known as constructors, which are invoked to construct objects from the class.
  • 6. Objects in OOP  An object has a unique identity, state, and behaviors.  The state of an object consists of a set of data fields (also known as properties) with their current values.  The behavior of an object is defined by a set of functions
  • 7. Class and Object  A class is template that defines what an object’s data and function will be. A C++ class uses variables to define data fields, and functions to define behavior.  An object is an instance of a class (the terms object and instance are often interchangeable).
  • 8. UML Diagram for Class and Object Circle radius: double Circle() Circle(newRadius: double) getArea(): double circle1: Circle radius: 10 Class name Data fields Constructors and Methods circle2: Circle radius: 25 circle3: Circle radius: 125
  • 9. Class in C++ - Example
  • 10. Class in C++ - Example class Circle { public: // The radius of this circle double radius; // Construct a circle object Circle() { radius = 1; } // Construct a circle object Circle(double newRadius) { radius = newRadius; } // Return the area of this circle double getArea() { return radius * radius * 3.14159; } }; Data field Function Constructors
  • 11. Class is a Type  You can use primitive data types to define variables.  You can also use class names to declare object names. In this sense, a class is an abstract type, data type or user-defined data type.
  • 12. Class Data Members and Member Functions  The data items within a class are called data members or data fields or instance variables  Member functions are functions that are included within a class. Also known as instance functions.
  • 13. Object Creation - Instantiation  In C++, you can assign a name when creating an object.  A constructor is invoked when an object is created.  The syntax to create an object using the no-arg constructor is ClassName objectName;  Defining objects in this way means creating them. This is also called instantiating them.
  • 14. A Simple Program – Object Creation class Circle { private: double radius; public: Circle() { radius = 5.0; } double getArea() { return radius * radius * 3.14159; } }; Object InstanceC1 : C1 radius: 5.0 void main() { Circle C1; //C1.radius = 10; can’t access private member outside the class cout<<“Area of circle = “<<C1.getArea(); } Allocate memory for radius
  • 15. Constructors  In object-oriented programming, a constructor in a class is a special function used to create an object. Constructor has exactly the same name as the defining class  Constructors can be overloaded (i.e., multiple constructors with different signatures), making it easy to construct objects with different initial data values.  A class may be declared without constructors. In this case, a no-argument constructor with an empty body is implicitly declared in the class known as default constructor  Note: Default constructor is provided automatically only if no constructors are explicitly declared in the class.
  • 16. Constructors’ Properties  Constructors must have the same name as the class itself.  Constructors do not have a return type—not even void.  Constructors play the role of initializing objects.
  • 17. Object Member Access Operator  After object creation, its data and functions can be accessed (invoked) using the (.) operator, also known as the object member access operator.  objectName.dataField references a data field in the object  objectName.function() invokes a function on the object
  • 18. A Simple Program – Accessing Members class Circle { private: double radius; public: Circle() { radius = 5.0; } double getArea() { return radius * radius * 3.14159; } }; Object InstanceC1 : C1 radius: 5.0 void main() { Circle C1; //C1.radius = 10; can’t access private member outside the class cout<<“Area of circle = “<<C1.getArea(); } Allocate memory for radius
  • 19. Access Modifiers  Access modifiers are used to set access levels for classes, variables, methods and constructors  private, public, and protected  In C++, default accessibility is private
  • 20. Data Hiding - Data Field Encapsulation  A key feature of OOP is data hiding, which means that data is concealed within a class so that it cannot be accessed mistakenly by functions outside the class.  To prevent direct modification of class attributes (outside the class), the primary mechanism for hiding data is to put it in a class and make it private using private keyword. This is known as data field encapsulation.
  • 21. Hidden from Whom?  Data hiding means hiding data from parts of the program that don’t need to access it. More specifically, one class’s data is hidden from other classes.  Data hiding is designed to protect well-intentioned programmers from mistakes.
  • 22. A Simple Program – Accessing Member Function class Circle { private: double radius; public: Circle() { radius = 5.0; } double getArea() { return radius * radius * 3.14159; } }; Object InstanceC1 : C1 radius: 5.0 void main() { Circle C1; //C1.radius = 10; can’t access private member outside the class cout<<“Area of circle = “<<C1.getArea(); } Allocate memory for radius
  • 23. A Simple Program – Default Constructor class Circle { private: double radius; public: double getArea() { return radius * radius * 3.14159; } }; // No Constructor Here Object InstanceC1 void main() { Circle C1; //C1.radius = 10; can’t access private member outside the class cout<<“Area of circle = “<<C1.getArea(); } //Default Constructor Circle() { } : C1 radius: Any Value Allocate memory for radius
  • 24. Object Construction with Arguments  The syntax to declare an object using a constructor with arguments is ClassName objectName(arguments);  For example, the following declaration creates an object named circle1 by invoking the Circle class’s constructor with a specified radius 5.5. Circle circle1(5.5);
  • 25. A Simple Program – Constructor with Arguments class Circle { private: double radius; public: Circle(double rad) { radius = rad; } double getArea() { return radius * radius * 3.14159; } }; Object InstanceC1 : C1 radius: 9.0 void main() { Circle C1(9.0); //C1.radius = 10; can’t access private member outside the class cout<<“Area of circle = “<<C1.getArea(); } Allocate memory for radius
  • 26. Output of the following Program? class Circle { private: double radius; public: Circle(double rad) { radius = rad; } double getArea() { return radius * radius * 3.14159; } }; void main() { Circle C1; cout<<“Area of circle = “<<C1.getArea(); }
  • 27. Constructor Overloading class Circle { private: double radius; public: Circle () { radius = 1; } Circle(double rad) { radius = rad; } double getArea() { return radius * radius * 3.14159; } }; void main() { Circle C2(8.0); Circle C1; cout<<“Area of circle = “<<C1.getArea(); }
  • 28. The this Pointer class Circle { private: double radius; public: Circle(double radius) { this->radius = radius; } double getArea() { return radius * radius * 3.14159; } }; void main() { Circle C1(99.0); cout<<“Area of circle = “<<C1.getArea(); }
  • 29. The this Pointer  this is keyword, which is a special built-in pointer that references to the calling object.  The this pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions.  Can be used to access instance variables within constructors and member functions
  • 30. Exercise Design a class named Account that contains:  A private int data field named id for the account (default 0)  A private double data field balance for the account (default 0)  A private double data field named annualInterestRate that stores the current interest rate (default 0).  A no-arg constructor that creates a default account.  A constructor that creates an account with the specified id, initial balance, and annual interest rate.  A function named getAnnualInterestRate() that returns the annual interest rate.  A function named withdraw that withdraws a specified amount from the account.  A function named deposit that deposits a specified amount to the account.  A function named show to print all attribute values  Implement the class. Write a test program that creates an Account object with an account ID of 1122, a balance of $20,000, and an annual interest rate of 4.5%. Use the withdraw method to withdraw $2,500, use the deposit method to deposit $3,000, and print the balance, the Annual interest, and the date when this account was created.
  • 31.  (Algebra: quadratic equations) Design a class named QuadraticEquation for a quadratic equation. The class contains:  Private data fields a, b, and c that represents three coefficients.  A constructor for the arguments of a, b, and c.  A function named getDiscriminant() that returns the discriminant, which is b2 – 4ac  The functions named getRoot1() and getRoot2() for returning two roots of the equation  Implement the class. Write a test program that prompts the user to enter values for a, b, and c and displays the result based on the discriminant. If the discriminant is positive, display the two roots. If the discriminant is 0, display the one root. Otherwise, display “The equation has no roots”. Exercise