SlideShare une entreprise Scribd logo
1  sur  26
CLASS OBJECTS,
CONSTRUCTOR &
DESTRUCTOR
Object Oriented Programming
COMSATS Institute of Information Technology
Book Class

Object Oriented Programming

#include <iostream.h>
#include <string.h>
• Data Hiding
class book{
– Data is concealed within the class
private:
char name[25];
– Cannot be access by function
int pages;
outside the class
float price;
– Primary mechanism to hide data
public:
is to make it private
void changeName(char *n){
– Private data and function can
strcpy(name, n);
Class
only be access from within the
}
Definition
class
void changePages(int p){
pages = p;
}
void changePrice(float p){
price = p;
}
void display(){
cout<<"name = "<<name<<" pages = "<<pages<<" price = "<<price<<endl;
}
};
2
CLASS DATA


The class book contain three data items
 char

Object Oriented Programming

name[15];
 int pages;
 float price;

There can be any number of data members in a
class just as in structure
 There data member lie under keyword private, so
they can be accessed from within the class, but
not outside


3
MEMBER FUNCTION
These functions are included in a class
 There are four member functions in class book


*n)
 changePages(int p)
 changePrice(float p)
 display()


Object Oriented Programming

 changeName(char

There functions are followed by a keyword public, so
they can be accessed outside the class

4
CLASS DATA AND MEMBER
FUNCTION
Function are public and data is private
 Data is hidden so that it can be safe from accidential
manipulation
 Functions operates on data are public so they can be
accessed from outside the class


Object Oriented Programming

5
DEFINING OBJECTS
The first statement in
void main(){
book b1;
main() book b1; defines an
b1.changeName("Operating System");
objects, b1 of class book
b1.changePages(500);
 Remember that the
b1.changePrice(150.56);
definition of the class book
b1.display();
}
does not create any
objects.


Object Oriented Programming

• The definition only describes how objects will look when
they are created, just as a structure definition describes
how a structure will look but doesn’t create any structure
6
variables.
CONT.
Defining an object is similar to defining a variable of
any data type: Space is set aside for it in memory e.g.
int x;
 Defining objects in this way (book b1;) means creating
them, also called instantiating them
 An object is an instance (that is, a specific example) of
a class. Objects are sometimes called instance
variables.


Object Oriented Programming

7
CALLING MEMBER FUNCTIONS
•

The next four statements in main() call the member
function
b1.changeName("Operating System");
– b1.changePages(500);
– b1.changePrice(150.56);
– b1.display();
–

•
•

don’t look like normal function calls
This syntax is used to call a member function that is
associated with a specific object
It doesn’t make sense to say
–

changeName("Operating System");

because a member function is always called
to act on a specific object, not on the class in
8
general

Object Oriented Programming

•
CONT.
To use a member function, the dot operator (the
period) connects the object name and the member
function.
 The syntax is similar to the way we refer to structure
members, but the parentheses signal that we’re
executing a member function rather than referring to
a data item.
 The dot operator is also called the class member access
operator.


Object Oriented Programming

9
MESSAGE


Object Oriented Programming

Some object-oriented languages refer to calls to
member functions as messages. Thus the call
b1.display();
can be thought of as sending a message to s1
telling it to show its data.

10
EXAMPLE PROGRAMS

Object Oriented Programming

Distance as object

11
Object Oriented Programming

12
Object Oriented Programming

13
CONSTRUCTORS
The Distance example shows two ways that member
functions can be used to give values to the data items
in an object

•

It is convenient if an object can initialize itself when
it’s first created, without requiring a separate call to a
member function

•

Automatic initialization is carried out using a special
member function called a constructor.

•

A constructor is a member function that is executed
automatically whenever an object is created.

Object Oriented Programming

•

14
Object Oriented Programming

A COUNTER EXAMPLE

15
Object Oriented Programming

16
AUTOMATIC INITIALIZATION
An object of type Counter is first created, we want its
count to be initialized to 0
 We could provide a set_count() function to do this and
call it with an argument of 0, or we could provide a
zero_count() function, which would always set count to
0.
 Such functions would need to be executed every time
we created a Counter object


Object Oriented Programming

Counter c1; //every time we do this,
c1.zero_count(); //we must do this too

17
CONT.

A programmer may forget to initialize the object after
creating it
 It’s more reliable and convenient to cause each object to
initialize itself when it’s created
 In the Counter class, the constructor Counter() is called
automatically whenever a new object of type Counter is
created
 Thus in main() the statement


creates two objects of type Counter. As each is created,
its constructor, Counter(), is executed.
 This function sets the count variable to 0.

Object Oriented Programming

Counter c1, c2;

18
CONSTRUCTOR NAME


First, constructor name must be same as the name of
class
 This

Second, no return type is used for constructors
 Why

Object Oriented Programming



is one way the compiler knows they are constructors.

not? Since the constructor is called automatically by the
system, there’s no program for it to return anything to; a
return value wouldn’t make sense.
 This is the second way the compiler knows they are
constructors.

19
INITIALIZER LIST
One of the most common tasks a constructor carries
out is initializing data members
 In the Counter class the constructor must initialize the
count member to 0.
 The initialization takes place following the member
function declarator but before the function body.
 Initialization in constructor’s function body


Object Oriented Programming

Counter()
{ count = 0; }
this is not the preferred approach (although it does work).

20
CONT.
•

It’s preceded by a colon. The value is placed in
parentheses following the member data.

•

If multiple members must be initialized, they’re
separated by commas.
–

someClass() : m1(7), m2(33), m2(4) ←initializer list
initializer list

Object Oriented Programming

Counter() : count(0)
{ }

{}

21
CONSTRUCTOR


Constructor:
 Public



Function overloading

Object Oriented Programming

function member
 called when a new object is created (instantiated).
 Initialize data members.
 Same name as class
 No return type
 Several constructors

22
CONSTRUCTOR (CONT…)

Constructor with no
argument
Constructor with one
argument

Object Oriented Programming

class Circle
{
private:
double radius;
public:
Circle();
Circle(int r);
void setRadius(double r);
double getDiameter();
double getArea();
double getCircumference();
};

23
DESTRUCTORS


You might guess that another function is called
automatically when an object is destroyed. This is
indeed the case. Such a function is called a destructor
Object Oriented Programming

The most common
use of destructors is
to deallocate memory
that was allocated for
the object by the
constructor

class Foo
{
private:
int data;
public:
Foo() : data(0) //constructor (same name as class)
{}
~Foo() //destructor (same name with tilde)
{}
};
24
DESTRUCTORS
 Destructors

member function
 Same name as class
 Preceded with tilde (~)
 No arguments
 No return value
 Cannot be overloaded
 Before system reclaims object’s memory
 Reuse memory for new objects
 Mainly used to de-allocate dynamic memory locations

Object Oriented Programming

 Special

25
DESTRUCTORS (CONT…)

destructor

Object Oriented Programming

class Circle
{
private:
double radius;
public:
Circle();
~Circle();
void setRadius(double r);
double getDiameter();
double getArea();
double getCircumference();
};

26

Contenu connexe

Tendances

constructor with default arguments and dynamic initialization of objects
constructor with default arguments and dynamic initialization of objectsconstructor with default arguments and dynamic initialization of objects
constructor with default arguments and dynamic initialization of objects
Kanhaiya Saxena
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
Haresh Jaiswal
 

Tendances (20)

C++ Constructor destructor
C++ Constructor destructorC++ Constructor destructor
C++ Constructor destructor
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programming
 
Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Constructor and Destructor in c++
Constructor  and Destructor in c++Constructor  and Destructor in c++
Constructor and Destructor in c++
 
constructor and destructor
constructor and destructorconstructor and destructor
constructor and destructor
 
constructor with default arguments and dynamic initialization of objects
constructor with default arguments and dynamic initialization of objectsconstructor with default arguments and dynamic initialization of objects
constructor with default arguments and dynamic initialization of objects
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
 
Constructor
ConstructorConstructor
Constructor
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
 
vb.net Constructor and destructor
vb.net Constructor and destructorvb.net Constructor and destructor
vb.net Constructor and destructor
 
Constructor and destructor in oop
Constructor and destructor in oop Constructor and destructor in oop
Constructor and destructor in oop
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
C# Constructors
C# ConstructorsC# Constructors
C# Constructors
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 

En vedette (14)

Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
 
OOPS
OOPSOOPS
OOPS
 
What is c
What is cWhat is c
What is c
 
Dynamics allocation
Dynamics allocationDynamics allocation
Dynamics allocation
 
Inheritance in OOPS
Inheritance in OOPSInheritance in OOPS
Inheritance in OOPS
 
Ashish oot
Ashish ootAshish oot
Ashish oot
 
Oop concepts
Oop conceptsOop concepts
Oop concepts
 
01 introduction to oop and java
01 introduction to oop and java01 introduction to oop and java
01 introduction to oop and java
 
Inheritance
InheritanceInheritance
Inheritance
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
 
Inheritance
InheritanceInheritance
Inheritance
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 

Similaire à Oop lec 5-(class objects, constructor & destructor)

Similaire à Oop lec 5-(class objects, constructor & destructor) (20)

[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
Constructor,destructors cpp
Constructor,destructors cppConstructor,destructors cpp
Constructor,destructors cpp
 
chapter-9-constructors.pdf
chapter-9-constructors.pdfchapter-9-constructors.pdf
chapter-9-constructors.pdf
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
constructor.ppt
constructor.pptconstructor.ppt
constructor.ppt
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
 
C questions
C questionsC questions
C questions
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptx
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
C++ training
C++ training C++ training
C++ training
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
Constructor&amp; destructor
Constructor&amp; destructorConstructor&amp; destructor
Constructor&amp; destructor
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Lab 6- Constructors in c++ . IST .pptx
Lab 6- Constructors in c++ .  IST  .pptxLab 6- Constructors in c++ .  IST  .pptx
Lab 6- Constructors in c++ . IST .pptx
 
OOP.pptx
OOP.pptxOOP.pptx
OOP.pptx
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
 
Class and object C++.pptx
Class and object C++.pptxClass and object C++.pptx
Class and object C++.pptx
 
Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
 

Plus de Asfand Hassan

Pak US relation 130411005046-phpapp01
Pak US relation 130411005046-phpapp01Pak US relation 130411005046-phpapp01
Pak US relation 130411005046-phpapp01
Asfand Hassan
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]
Asfand Hassan
 
Oop lec 3(structures)
Oop lec 3(structures)Oop lec 3(structures)
Oop lec 3(structures)
Asfand Hassan
 
Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)
Asfand Hassan
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)
Asfand Hassan
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]
Asfand Hassan
 

Plus de Asfand Hassan (13)

Pak US relation 130411005046-phpapp01
Pak US relation 130411005046-phpapp01Pak US relation 130411005046-phpapp01
Pak US relation 130411005046-phpapp01
 
Chap5java5th
Chap5java5thChap5java5th
Chap5java5th
 
Chap6java5th
Chap6java5thChap6java5th
Chap6java5th
 
Chap4java5th
Chap4java5thChap4java5th
Chap4java5th
 
Chap3java5th
Chap3java5thChap3java5th
Chap3java5th
 
Chap2java5th
Chap2java5thChap2java5th
Chap2java5th
 
Chap1java5th
Chap1java5thChap1java5th
Chap1java5th
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]
 
Oop lec 3(structures)
Oop lec 3(structures)Oop lec 3(structures)
Oop lec 3(structures)
 
Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)
 
Oop lec 1
Oop lec 1Oop lec 1
Oop lec 1
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]
 

Dernier

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Dernier (20)

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
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_...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
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
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
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
 

Oop lec 5-(class objects, constructor & destructor)

  • 1. CLASS OBJECTS, CONSTRUCTOR & DESTRUCTOR Object Oriented Programming COMSATS Institute of Information Technology
  • 2. Book Class Object Oriented Programming #include <iostream.h> #include <string.h> • Data Hiding class book{ – Data is concealed within the class private: char name[25]; – Cannot be access by function int pages; outside the class float price; – Primary mechanism to hide data public: is to make it private void changeName(char *n){ – Private data and function can strcpy(name, n); Class only be access from within the } Definition class void changePages(int p){ pages = p; } void changePrice(float p){ price = p; } void display(){ cout<<"name = "<<name<<" pages = "<<pages<<" price = "<<price<<endl; } }; 2
  • 3. CLASS DATA  The class book contain three data items  char Object Oriented Programming name[15];  int pages;  float price; There can be any number of data members in a class just as in structure  There data member lie under keyword private, so they can be accessed from within the class, but not outside  3
  • 4. MEMBER FUNCTION These functions are included in a class  There are four member functions in class book  *n)  changePages(int p)  changePrice(float p)  display()  Object Oriented Programming  changeName(char There functions are followed by a keyword public, so they can be accessed outside the class 4
  • 5. CLASS DATA AND MEMBER FUNCTION Function are public and data is private  Data is hidden so that it can be safe from accidential manipulation  Functions operates on data are public so they can be accessed from outside the class  Object Oriented Programming 5
  • 6. DEFINING OBJECTS The first statement in void main(){ book b1; main() book b1; defines an b1.changeName("Operating System"); objects, b1 of class book b1.changePages(500);  Remember that the b1.changePrice(150.56); definition of the class book b1.display(); } does not create any objects.  Object Oriented Programming • The definition only describes how objects will look when they are created, just as a structure definition describes how a structure will look but doesn’t create any structure 6 variables.
  • 7. CONT. Defining an object is similar to defining a variable of any data type: Space is set aside for it in memory e.g. int x;  Defining objects in this way (book b1;) means creating them, also called instantiating them  An object is an instance (that is, a specific example) of a class. Objects are sometimes called instance variables.  Object Oriented Programming 7
  • 8. CALLING MEMBER FUNCTIONS • The next four statements in main() call the member function b1.changeName("Operating System"); – b1.changePages(500); – b1.changePrice(150.56); – b1.display(); – • • don’t look like normal function calls This syntax is used to call a member function that is associated with a specific object It doesn’t make sense to say – changeName("Operating System"); because a member function is always called to act on a specific object, not on the class in 8 general Object Oriented Programming •
  • 9. CONT. To use a member function, the dot operator (the period) connects the object name and the member function.  The syntax is similar to the way we refer to structure members, but the parentheses signal that we’re executing a member function rather than referring to a data item.  The dot operator is also called the class member access operator.  Object Oriented Programming 9
  • 10. MESSAGE  Object Oriented Programming Some object-oriented languages refer to calls to member functions as messages. Thus the call b1.display(); can be thought of as sending a message to s1 telling it to show its data. 10
  • 11. EXAMPLE PROGRAMS Object Oriented Programming Distance as object 11
  • 14. CONSTRUCTORS The Distance example shows two ways that member functions can be used to give values to the data items in an object • It is convenient if an object can initialize itself when it’s first created, without requiring a separate call to a member function • Automatic initialization is carried out using a special member function called a constructor. • A constructor is a member function that is executed automatically whenever an object is created. Object Oriented Programming • 14
  • 15. Object Oriented Programming A COUNTER EXAMPLE 15
  • 17. AUTOMATIC INITIALIZATION An object of type Counter is first created, we want its count to be initialized to 0  We could provide a set_count() function to do this and call it with an argument of 0, or we could provide a zero_count() function, which would always set count to 0.  Such functions would need to be executed every time we created a Counter object  Object Oriented Programming Counter c1; //every time we do this, c1.zero_count(); //we must do this too 17
  • 18. CONT. A programmer may forget to initialize the object after creating it  It’s more reliable and convenient to cause each object to initialize itself when it’s created  In the Counter class, the constructor Counter() is called automatically whenever a new object of type Counter is created  Thus in main() the statement  creates two objects of type Counter. As each is created, its constructor, Counter(), is executed.  This function sets the count variable to 0. Object Oriented Programming Counter c1, c2; 18
  • 19. CONSTRUCTOR NAME  First, constructor name must be same as the name of class  This Second, no return type is used for constructors  Why Object Oriented Programming  is one way the compiler knows they are constructors. not? Since the constructor is called automatically by the system, there’s no program for it to return anything to; a return value wouldn’t make sense.  This is the second way the compiler knows they are constructors. 19
  • 20. INITIALIZER LIST One of the most common tasks a constructor carries out is initializing data members  In the Counter class the constructor must initialize the count member to 0.  The initialization takes place following the member function declarator but before the function body.  Initialization in constructor’s function body  Object Oriented Programming Counter() { count = 0; } this is not the preferred approach (although it does work). 20
  • 21. CONT. • It’s preceded by a colon. The value is placed in parentheses following the member data. • If multiple members must be initialized, they’re separated by commas. – someClass() : m1(7), m2(33), m2(4) ←initializer list initializer list Object Oriented Programming Counter() : count(0) { } {} 21
  • 22. CONSTRUCTOR  Constructor:  Public  Function overloading Object Oriented Programming function member  called when a new object is created (instantiated).  Initialize data members.  Same name as class  No return type  Several constructors 22
  • 23. CONSTRUCTOR (CONT…) Constructor with no argument Constructor with one argument Object Oriented Programming class Circle { private: double radius; public: Circle(); Circle(int r); void setRadius(double r); double getDiameter(); double getArea(); double getCircumference(); }; 23
  • 24. DESTRUCTORS  You might guess that another function is called automatically when an object is destroyed. This is indeed the case. Such a function is called a destructor Object Oriented Programming The most common use of destructors is to deallocate memory that was allocated for the object by the constructor class Foo { private: int data; public: Foo() : data(0) //constructor (same name as class) {} ~Foo() //destructor (same name with tilde) {} }; 24
  • 25. DESTRUCTORS  Destructors member function  Same name as class  Preceded with tilde (~)  No arguments  No return value  Cannot be overloaded  Before system reclaims object’s memory  Reuse memory for new objects  Mainly used to de-allocate dynamic memory locations Object Oriented Programming  Special 25
  • 26. DESTRUCTORS (CONT…) destructor Object Oriented Programming class Circle { private: double radius; public: Circle(); ~Circle(); void setRadius(double r); double getDiameter(); double getArea(); double getCircumference(); }; 26