SlideShare a Scribd company logo
1 of 20
Objects and Classes
Objectives
 To learn how to create objects with new
 To learn the use of destructor
 To study constructor initializer list
 To study accessor and mutator methods
 To see the working of Default copy constructor and
Member-wise Copy
 To learn the scope of variables
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;
Circle *c2 = new Circle();
cout<<“Area of circle = “<<c1.getArea()<<c2.getArea();
}
Allocate memory
for radius
Object InstanceC2
: C2
radius: 5.0
Allocate memory
for radius
Destructor
 A destructor is a member function with the same
name as its class prefixed by a ~ (tilde).
 Destructors are usually used to deallocate memory
and do other cleanup for a class object and its class
members when the object is destroyed.
 A destructor is called for a class object when that
object passes out of scope or is explicitly deleted.
Destructor
 A destructor takes no arguments and has no return
type.
 Destructors cannot be declared const, volatile, const
or static. A destructor can be declared virtual or pure
virtual.
 If no user-defined destructor exists for a class and one
is needed, the compiler implicitly declares a destructor.
This implicitly declared destructor is an inline public
member of its class.
Destructor - Example
class Circle
{
private:
double radius;
public:
Circle();
Circle(double);
double getArea();
~Circle();
};
Circle::Circle()
{ radius = 1.0; }
Circle::Circle(double rad)
{ radius = rad; }
double Circle::getArea()
{ return radius * radius * 3.14; }
Circle::~Circle() { cout<<“Destructor called”; }
void main()
{
Circle c1;
Circle *c2 = new Circle(10.7);
cout<<“Area of circle = “<<c1.getArea();
cout<<“Area of circle = “<<c2.getArea();
}
Class
declaration
Class
Implementation
Constructor Initializer
Circle(): radius(1)
{
}
Circle()
{
radius = 1;
}
Same as
(a) (b)
Member Initialization List
 One task of the Constructor is to initialize data members
 Example: for class Circle
Circle(){ radius = 1.0; }
But it is not preferred approach. The preferred approach is
Circle(): radius(1.0)
{ }
 If multiple members be to initialize, separate them by
commas. The result is the initializer list (also known as
member-initialization list)
Circle(): radius(1.0), area(0.0)
{ } Member
Initialization List
Reasons for Constructor Initializers
 In the initializer list, members initialized with given
values before the constructor even starts to execute
 This is important in some situations e.g. the initializer
list is the only way to initialize const member data
and references
 However, actions more complicated than simple
initialization must be carried out in the constructor
body, as with ordinary functions.
Accessor (getter) and Mutator (Setter) Functions
 Colloquially, a get function is referred to as a getter (or
accessor), and a set function is referred to as a setter (or
mutator).
 A get function has the following header:
returnType getPropertyName(){ }
 A set function has the following header:
void setPropertyName(dataType propertyValue){ }
Example
class VehiclePart{
private:
int modelno; int partno; float cost;
public:
VehiclePart():modelno(0),partno(0),cost(0.0)
{ }
void setModelNo(int mn){ modelno = mn; }
void setPartNo(int pn){ partno = pn; }
void setCost(float c){ cost = c; }
void setVehDetail(int mn, int pn, float c)
{ modelno = mn; partno = pn; cost = c; }
int getModelNo(){ return modelno; }
int getPartNo(){ return partno; }
float getCost(){ return cost; }
void showVehDetail()
{ cout<<modelno<<partno<<cost; }
};
Mutator
Functions
Accessor
Functions
Example
class Book{
private:
int bookID, totalPage;
float price;
public:
Book():bookID(0),totalPage(0),price(0.0)
{ }
void setBookID(int bid){ bookID = bid; }
void setPages (int pn){ totalPage = pn; }
void setPrice(float p){ price = p; }
int getBookID(){ return bookID; }
int getPages(){ return totalPages; }
float getPrice(){ return price; }
};
Mutator
Functions
Accessor
Functions
Default copy constructor
 A type of constructor that is used to initialize an
object with another object of the same type is
known as default copy constructor.
 It is by default available in all classes
 syntax is ClassName(ClassName &Variable)
Default Copy Constructor - Example
class Distance {
private:
int feet; float inches;
public:
Distance():feet(0),inches(0.0)
{ }
Distance(int ft, float in): feet(ft), inches(in)
{ }
Distance(Distance &d)
{ feet = d.feet; inches = d.inches; }
void showDistance()
{
cout<<“Feet = “<<feet;
cout<<“Inches=“<<inches;
}
};
void main() {
Distance dist1(11,22.8);
Distance dist2(dist1);
Distance dist3 = dist1;
dist1.showDistance();
dist2.showDistance();
dist3.showDistance();
}
Memberwise Copy
 Another different format has exactly the same
effect, causing object to be copied member-by-
member into other object.
 Remember, object1 = object2 will not invoke the
copy constructor. However, this statement is legal
and simply assigns the values of object2 to object1,
member-by-member. This is the task of the
overloaded assignment operator (=).
Memberwise Copy - Example
class Distance
{
private:
int feet; float inches;
public:
Distance():feet(0),inches(0.0)
{ }
Distance(int ft, float in): feet(ft), inches(in)
{ }
void showDistance()
{
cout<<“Feet = “<<feet;
cout<<“Inches=“<<inches;
}
};
void main()
{
Distance dist1(11,22.8);
Distance dist2(dist1);
Distance dist3 = dist1;
Distance dist4;
dist4 = dist1;
dist1.showDistance();
dist2.showDistance();
dist3.showDistance();
dist4.showDistance();
}
Returning Objects from Function - Example
class Distance {
private:
int feet;
public:
Distance():feet(0)
{ }
Distance(int ft): feet(ft)
{ }
Distance addDist(Distance d)
{
Distance temp;
temp.feet = this->feet + d.feet;
return temp;
}
void showDistance()
{ cout<<“Feet = “<<feet; }
};
void main()
{
Distance dist1, dist3;
Distance dist2(11);
dist3 = dist1.addDist(dist2);
dist1.showDistance();
dist2.showDistance();
dist3.showDistance();
}
The Scope of Variables
Global variables are declared outside all functions
and are accessible to all functions in its scope. The
scope of a global variable starts from its declaration
and continues to the end of the program.
Local variables are defined inside functions. The
scope of a local variable starts from its declaration
and continues to the end of the block that contains
the variable.
The Scope of Variables
The data fields are declared as variables and are accessible to
all constructors and functions in the class.
Data fields and functions can be declared in any order in a
class. For example, all the following declarations are the same:
class Circle
{
public:
Circle();
Circle(double);
private:
double radius;
public:
double getArea();
double getRadius();
void setRadius(double);
};
(a) (b)
class Circle
{
private:
double radius;
public:
double getArea();
double getRadius();
void setRadius(double);
public:
Circle();
Circle(double);
};
class Circle
{
public:
Circle();
Circle(double);
double getArea();
double getRadius();
void setRadius(double);
private:
double radius;
};
(c)
The Scope of local variables in a class
Local variables are declared and used inside a
function locally.
In a class, if a local variable has the same name as
a data field, the local variable takes precedence
and the data field with the same name is hidden.

More Related Content

What's hot

JDD 2016 - Pawel Byszewski - Kotlin, why?
JDD 2016 - Pawel Byszewski - Kotlin, why?JDD 2016 - Pawel Byszewski - Kotlin, why?
JDD 2016 - Pawel Byszewski - Kotlin, why?PROIDEA
 
Aho-Corasick string matching algorithm
Aho-Corasick string matching algorithmAho-Corasick string matching algorithm
Aho-Corasick string matching algorithmTakatoshi Kondo
 
The Ring programming language version 1.5.2 book - Part 34 of 181
The Ring programming language version 1.5.2 book - Part 34 of 181The Ring programming language version 1.5.2 book - Part 34 of 181
The Ring programming language version 1.5.2 book - Part 34 of 181Mahmoud Samir Fayed
 
Utilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationUtilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationSeven Peaks Speaks
 
The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210Mahmoud Samir Fayed
 
Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)RichardWarburton
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. StreamsDEVTYPE
 
The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212Mahmoud Samir Fayed
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в JavaDEVTYPE
 
Pads lab manual final
Pads lab manual finalPads lab manual final
Pads lab manual finalAhalyaR
 
Swift 3 Programming for iOS : subscript init
Swift 3 Programming for iOS : subscript initSwift 3 Programming for iOS : subscript init
Swift 3 Programming for iOS : subscript initKwang Woo NAM
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Calvin Cheng
 
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークGroovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークTsuyoshi Yamamoto
 

What's hot (20)

JDD 2016 - Pawel Byszewski - Kotlin, why?
JDD 2016 - Pawel Byszewski - Kotlin, why?JDD 2016 - Pawel Byszewski - Kotlin, why?
JDD 2016 - Pawel Byszewski - Kotlin, why?
 
Aho-Corasick string matching algorithm
Aho-Corasick string matching algorithmAho-Corasick string matching algorithm
Aho-Corasick string matching algorithm
 
The Ring programming language version 1.5.2 book - Part 34 of 181
The Ring programming language version 1.5.2 book - Part 34 of 181The Ring programming language version 1.5.2 book - Part 34 of 181
The Ring programming language version 1.5.2 book - Part 34 of 181
 
Javascript
JavascriptJavascript
Javascript
 
Utilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationUtilizing kotlin flows in an android application
Utilizing kotlin flows in an android application
 
The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202
 
The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210
 
Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Opp compile
Opp compileOpp compile
Opp compile
 
The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
Pads lab manual final
Pads lab manual finalPads lab manual final
Pads lab manual final
 
Pointers
PointersPointers
Pointers
 
P1
P1P1
P1
 
Swift 3 Programming for iOS : subscript init
Swift 3 Programming for iOS : subscript initSwift 3 Programming for iOS : subscript init
Swift 3 Programming for iOS : subscript init
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 
Php sql-android
Php sql-androidPhp sql-android
Php sql-android
 
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークGroovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトーク
 

Similar to oop objects_classes

Similar to oop objects_classes (20)

Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C++ classes
C++ classesC++ classes
C++ classes
 
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
 
C++ Classes Tutorials.ppt
C++ Classes Tutorials.pptC++ Classes Tutorials.ppt
C++ Classes Tutorials.ppt
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
Presentation on template and exception
Presentation  on template and exceptionPresentation  on template and exception
Presentation on template and exception
 
Pre zen ta sion
Pre zen ta sionPre zen ta sion
Pre zen ta sion
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
12
1212
12
 
ccc
cccccc
ccc
 
The STL
The STLThe STL
The STL
 
Inheritance in C++.ppt
Inheritance in C++.pptInheritance in C++.ppt
Inheritance in C++.ppt
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
 
Oo ps
Oo psOo ps
Oo ps
 
Refactoring - improving the smell of your code
Refactoring - improving the smell of your codeRefactoring - improving the smell of your code
Refactoring - improving the smell of your code
 

Recently uploaded

FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 

Recently uploaded (20)

FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 

oop objects_classes

  • 2. Objectives  To learn how to create objects with new  To learn the use of destructor  To study constructor initializer list  To study accessor and mutator methods  To see the working of Default copy constructor and Member-wise Copy  To learn the scope of variables
  • 3. 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; Circle *c2 = new Circle(); cout<<“Area of circle = “<<c1.getArea()<<c2.getArea(); } Allocate memory for radius Object InstanceC2 : C2 radius: 5.0 Allocate memory for radius
  • 4. Destructor  A destructor is a member function with the same name as its class prefixed by a ~ (tilde).  Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed.  A destructor is called for a class object when that object passes out of scope or is explicitly deleted.
  • 5. Destructor  A destructor takes no arguments and has no return type.  Destructors cannot be declared const, volatile, const or static. A destructor can be declared virtual or pure virtual.  If no user-defined destructor exists for a class and one is needed, the compiler implicitly declares a destructor. This implicitly declared destructor is an inline public member of its class.
  • 6. Destructor - Example class Circle { private: double radius; public: Circle(); Circle(double); double getArea(); ~Circle(); }; Circle::Circle() { radius = 1.0; } Circle::Circle(double rad) { radius = rad; } double Circle::getArea() { return radius * radius * 3.14; } Circle::~Circle() { cout<<“Destructor called”; } void main() { Circle c1; Circle *c2 = new Circle(10.7); cout<<“Area of circle = “<<c1.getArea(); cout<<“Area of circle = “<<c2.getArea(); } Class declaration Class Implementation
  • 8. Member Initialization List  One task of the Constructor is to initialize data members  Example: for class Circle Circle(){ radius = 1.0; } But it is not preferred approach. The preferred approach is Circle(): radius(1.0) { }  If multiple members be to initialize, separate them by commas. The result is the initializer list (also known as member-initialization list) Circle(): radius(1.0), area(0.0) { } Member Initialization List
  • 9. Reasons for Constructor Initializers  In the initializer list, members initialized with given values before the constructor even starts to execute  This is important in some situations e.g. the initializer list is the only way to initialize const member data and references  However, actions more complicated than simple initialization must be carried out in the constructor body, as with ordinary functions.
  • 10. Accessor (getter) and Mutator (Setter) Functions  Colloquially, a get function is referred to as a getter (or accessor), and a set function is referred to as a setter (or mutator).  A get function has the following header: returnType getPropertyName(){ }  A set function has the following header: void setPropertyName(dataType propertyValue){ }
  • 11. Example class VehiclePart{ private: int modelno; int partno; float cost; public: VehiclePart():modelno(0),partno(0),cost(0.0) { } void setModelNo(int mn){ modelno = mn; } void setPartNo(int pn){ partno = pn; } void setCost(float c){ cost = c; } void setVehDetail(int mn, int pn, float c) { modelno = mn; partno = pn; cost = c; } int getModelNo(){ return modelno; } int getPartNo(){ return partno; } float getCost(){ return cost; } void showVehDetail() { cout<<modelno<<partno<<cost; } }; Mutator Functions Accessor Functions
  • 12. Example class Book{ private: int bookID, totalPage; float price; public: Book():bookID(0),totalPage(0),price(0.0) { } void setBookID(int bid){ bookID = bid; } void setPages (int pn){ totalPage = pn; } void setPrice(float p){ price = p; } int getBookID(){ return bookID; } int getPages(){ return totalPages; } float getPrice(){ return price; } }; Mutator Functions Accessor Functions
  • 13. Default copy constructor  A type of constructor that is used to initialize an object with another object of the same type is known as default copy constructor.  It is by default available in all classes  syntax is ClassName(ClassName &Variable)
  • 14. Default Copy Constructor - Example class Distance { private: int feet; float inches; public: Distance():feet(0),inches(0.0) { } Distance(int ft, float in): feet(ft), inches(in) { } Distance(Distance &d) { feet = d.feet; inches = d.inches; } void showDistance() { cout<<“Feet = “<<feet; cout<<“Inches=“<<inches; } }; void main() { Distance dist1(11,22.8); Distance dist2(dist1); Distance dist3 = dist1; dist1.showDistance(); dist2.showDistance(); dist3.showDistance(); }
  • 15. Memberwise Copy  Another different format has exactly the same effect, causing object to be copied member-by- member into other object.  Remember, object1 = object2 will not invoke the copy constructor. However, this statement is legal and simply assigns the values of object2 to object1, member-by-member. This is the task of the overloaded assignment operator (=).
  • 16. Memberwise Copy - Example class Distance { private: int feet; float inches; public: Distance():feet(0),inches(0.0) { } Distance(int ft, float in): feet(ft), inches(in) { } void showDistance() { cout<<“Feet = “<<feet; cout<<“Inches=“<<inches; } }; void main() { Distance dist1(11,22.8); Distance dist2(dist1); Distance dist3 = dist1; Distance dist4; dist4 = dist1; dist1.showDistance(); dist2.showDistance(); dist3.showDistance(); dist4.showDistance(); }
  • 17. Returning Objects from Function - Example class Distance { private: int feet; public: Distance():feet(0) { } Distance(int ft): feet(ft) { } Distance addDist(Distance d) { Distance temp; temp.feet = this->feet + d.feet; return temp; } void showDistance() { cout<<“Feet = “<<feet; } }; void main() { Distance dist1, dist3; Distance dist2(11); dist3 = dist1.addDist(dist2); dist1.showDistance(); dist2.showDistance(); dist3.showDistance(); }
  • 18. The Scope of Variables Global variables are declared outside all functions and are accessible to all functions in its scope. The scope of a global variable starts from its declaration and continues to the end of the program. Local variables are defined inside functions. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable.
  • 19. The Scope of Variables The data fields are declared as variables and are accessible to all constructors and functions in the class. Data fields and functions can be declared in any order in a class. For example, all the following declarations are the same: class Circle { public: Circle(); Circle(double); private: double radius; public: double getArea(); double getRadius(); void setRadius(double); }; (a) (b) class Circle { private: double radius; public: double getArea(); double getRadius(); void setRadius(double); public: Circle(); Circle(double); }; class Circle { public: Circle(); Circle(double); double getArea(); double getRadius(); void setRadius(double); private: double radius; }; (c)
  • 20. The Scope of local variables in a class Local variables are declared and used inside a function locally. In a class, if a local variable has the same name as a data field, the local variable takes precedence and the data field with the same name is hidden.