SlideShare a Scribd company logo
Object Oriented
Programming
with C++
Reema Thareja
© Oxford University Press 2015. All rights reserved.
Chapter Nine
Classes and Objects
© Oxford University Press 2015. All rights reserved.
INTRODUCTION
© Oxford University Press 2015. All rights reserved.
Classes form the building blocks of the object-oriented
programming paradigm. They simplify the development of large
and complex projects and help produce software which is easy to
understand, modular, re-usable, and easily expandable
Syntactically, classes are similar to structures, the only difference
between a structure and a class is that by default, members of a
class are private, while members of a structure are public.
Although there is no general rule as when to use a structure and
when to use a class, generally, C++ programmers use structures for
holding data and classes to hold data and functions.
SPECIFYING A CLASS
© Oxford University Press 2015. All rights reserved.
•A class is the basic mechanism to provide data encapsulation. Data
encapsulation is an important feature of object-oriented
programming paradigm.
•It binds data and member functions in a single entity in such a way
that data can be manipulated only through the functions defined in
that class.
•The process of specifying a class consists of two steps—class
declaration and function definitions (Fig.).
Class Declaration
The keyword class denotes that the class_name that follows
is user-defined data type. The body of the class is enclosed
within curly braces and terminated with a semicolon, as in
structures. Data members and functions are declared within
the body of the class.
© Oxford University Press 2015. All rights reserved.
Visibility Labels
• Data and functions are grouped under two sections :-Private
and Public data.
• Private Data:- All data members and member functions
declared private can be accessed only from within the class.
• They are strictly not accessible by any entity—function or
class—outside the class in which they have been declared. In
C++, data hiding is implemented through the private visibility
label.
• Public Data:- and functions that are public can be accessed
from outside the class.
• By default, members of the class, both data and function, are
private. If any visibility label is missing, they are automatically
treated as private members—private and public.
© Oxford University Press 2015. All rights reserved.
Defining a Function Inside the Class
• In this method, function declaration or prototype is replaced
with function definition inside the class.
• Though it increases the execution speed of the program, it
consumes more space.
• A function defined inside the class is treated as an inline
function by default, provided they do not fall into the restricted
category of inline functions.
© Oxford University Press 2015. All rights reserved.
Example:- Function inside the class
© Oxford University Press 2015. All rights reserved.
Defining a Function Outside the Class
• class_name:: and function_name tell the compiler that scope of
the function is restricted to the class_name. The name of the ::
operator is scope resolution operator.
• The importance of the :: is even more prominent in the
following cases.
• When different classes in the same program have functions
with the same name. In this case,it tells the compiler which
function belongs to which class to restrict the non-member
functions of the class to use its private members.
• It allow a member function of the class to call another member
function directly without using the dot operator.
© Oxford University Press 2015. All rights reserved.
Example:-Defining a function outside the class
© Oxford University Press 2015. All rights reserved.
CREATING OBJECTS
• To use a class, we must create variables of the class also
known as objects.
• The process of creating objects of the class is called class
instantiation.
• Memory is allocated only when we create object(s) of the
class.
• The syntax of defining an object (variable) of a class is as
follows:-class_name object_name; .
© Oxford University Press 2015. All rights reserved.
Example:- Object Creation.
© Oxford University Press 2015. All rights reserved.
ACCESSING OBJECT MEMBERS
• There are two types of class members—private and public.
• While private members can be only accessed through public
members, public members, on the other hand, can be called
from main() or any function outside the class.
• The syntax of calling an object member is as follows:-
object_name.function_name(arguments);
© Oxford University Press 2015. All rights reserved.
Example:- Calling of object.
© Oxford University Press 2015. All rights reserved.
Static Data Members
• When a data member is declared as static, the following must
be noted:-
• Irrespective of the number of objects created, only a
single copy of the static member is created in memory.
• All objects of a class share the static member.
• All static data members are initialized to zero when
the first object of that class is created.
• Static data members are visible only within the class but their
lifetime is the entire program.
© Oxford University Press 2015. All rights reserved.
Static Data Members
• Relevance:-Static data members are usually used to maintain
values that are common for the entire class. For example, to
keep a track of how many objects of a particular class has been
created.
• Place of Storage:-Although static data members are declared
inside a class, they are not considered to be a part of the
objects. Consequently, their declaration in the class is not
considered as their defination. A static data member is defined
outside the class. This means that even though the static data
member is declared in class scope, their defination persist in
the entire file. A static member has a file scope.
© Oxford University Press 2015. All rights reserved.
Static Data Members contd.
• However, since a static data member is declared inside the
class, they can be accessed only by using the class name and
the scope resolution operator.
© Oxford University Press 2015. All rights reserved.
Example:- Static data members
© Oxford University Press 2015. All rights reserved.
Static Member Functions
• It can access only the static members—data and/or
functions—declared in the same class.
• It cannot access non-static members because they belong to an
object but static functions have no object to work with.
• Since it is not a part of any object, it is called using the class
name and the scope resolution operator.
• As static member functions are not attached to an object, the
this pointer does not work on them.
• A static member function cannot be declared as virtual
function.
• A static member function can be declared with const, volatile
type qualifiers.
© Oxford University Press 2015. All rights reserved.
© Oxford University Press 2015. All rights reserved.
Static Object
• To initialize all the variables of an object to zero, we have two
techniques:-
• Make a constructor and explicitly set each variable to 0. We
will read about it in the next chapter.
• To declare the object as static, when an object of a class is
declared static, all its members are automatically initialized to
zero.
© Oxford University Press 2015. All rights reserved.
ARRAY OF OBJECTS
• Just as we have arrays of basic data types, C++ allows programmers
to create arrays of user-defined data types as well.
• We can declare an array of class student by simple writing student
s[20]; // assuming there are 20 students in a class.
• When this statement gets executed, the compiler will set aside
memory for storing details of 20 students.
• This means that in addition to the space required by member
functions, 20 * sizeof(student) bytes of consecutive memory
locations will be reserved for objects at the compile time.
• An individual object of the array of objects is referenced by using
an index, and the particular member is accessed using the dot
operator. Therefore, if we write, s[i].get_data() then the statement
when executed will take the details of the i th student.
© Oxford University Press 2015. All rights reserved.
OBJECTS AS FUNCTION ARGUMENTS
• Pass-by-value In this technique, a copy of the actual object is
created and passed to the called function.
• Therefore, the actual (object) and the formal (copy of object)
arguments are stored at different memory locations.
• This means that any changes made in formal object will not be
reflected in the actual object.
• Pass-by-reference In this method, the address of the object is
implicitly passed to the called function.
• Pass-by-address In this technique, the address of the object is
explicitly passed to the called function.
© Oxford University Press 2015. All rights reserved.
© Oxford University Press 2015. All rights
reserved.
© Oxford University Press 2015. All rights reserved.
RETURNING OBJECTS
• You can return an object using the following three methods:-
• Returning by value which makes a duplicate copy of the local
object.
• Returning by using a reference to the object. In this way, the
address of the object is passed implicitly to the calling
function.
• Returning by using the ‘this pointer’ which explicitly sends the
address of the object to the calling function.
© Oxford University Press 2015. All rights reserved.
Example:- Returning an object.
© Oxford University Press 2015. All rights reserved.
this POINTER
• C++ uses the this keyword to represent the object that invoked
the member function of the class.
• this pointer is an implicit parameter to all member functions
and can, therefore, be used inside a member function to refer
to the invoking object.
© Oxford University Press 2015. All rights reserved.
© Oxford University Press 2015. All rights reserved.
CONSTANT MEMBER FUNCTION
• Constant member functions are used when a particular
member function should strictly not attempt to change the
value of any of the class’s data member.
return_type function_name(arguments) const
• Note that the keyword const should be suffixed in function
header during declaration and defination.
© Oxford University Press 2015. All rights reserved.
© Oxford University Press 2015. All rights reserved.
CONSTANT PARAMETERS
• When we pass constant objects as parameters, then members
of the object—whether private or public—cannot be changed.
• This is even more important when we are passing an object to
a non-member function as in,
void increment(Employee e, float amt)
{ e.sal += amt;
}
• Hence, to prevent any changes by non-member of the class, we
must pass the object as a constant object. The function will
then receive a read-only copy of the object and will not be
allowed to make any changes to it. To pass a const object to
the increment function, we must write:-
void increment(Employee const e, float amt);
void increment(Employee const &e, float amt);
© Oxford University Press 2015. All rights reserved.
© Oxford University Press 2015. All rights reserved.
LOCAL CLASSES
• A local class is the class which is defined inside a function.
Till now, we were creating global classes since these were
defined above all the functions, including main().
• However, as the name implies, a local class is local to the
function in which it is defined and therefore is known or
accessible only in that function.
• There are certain guidelines that must be followed while using
local classes, which are as follows:-
• Local classes can use any global variable but along with the
scope resolution operator.
© Oxford University Press 2015. All rights reserved.
LOCAL CLASSES
• Local classes can use static variables declared inside the
function.
• Local classes cannot use automatic variables.
• Local classes cannot have static data members.
• Member functions must be defined inside the class.
• Private members of the class cannot be accessed by the
enclosing function
© Oxford University Press 2015. All rights reserved.
© Oxford University Press 2015. All rights reserved.
NESTED CLASSES
• C++ allows programmers to create a class inside another class.
This is called nesting of classes.
• When a class B is nested inside another class A, class B is not
allowed to access class A’s members. The following points
must be noted about nested classes:-
• A nested class is declared and defined inside another class.
• The scope of the inner class is restricted by the outer class.
• While declaring an object of inner class, the name of the inner
class must be preceded with the name of the outer class.
© Oxford University Press 2015. All rights reserved.
© Oxford University Press 2015. All rights reserved.
COMPLEX OBJECTS ( OBJECT COMPOSITION)
• Complex objects are objects that are built from smaller or simpler
objects
• In OOP, it is used for objects that have a has-a relationship to each
other. For ex, a car has-a metal frame, has-an engine, etc.
• Benefits
• Each individual class can be simple and straightforward.
• A class can focus on performing one specific task.
• The class is easier to write, debug, understand, and usable by other
programmers.
© Oxford University Press 2015. All rights reserved.
COMPLEX OBJECTS ( OBJECT COMPOSITION)
• While simpler classes can perform all the operations, the
complex class can be designed to coordinate the data flow
between simpler classes.
• It lowers the overall complexity of the complex object because
the main task of the complex object would then be to delegate
tasks to the sub-objects, who already know how to do them.
© Oxford University Press 2015. All rights reserved.
© Oxford University Press 2015. All rights reserved.
EMPTY CLASSES
• An empty class is one in which there are no data members and
no member functions. These type of classes are not frequently
used. However, at times, they may be used for exception
handling, discussed in a later chapter.
• The syntax of defining an empty class is as follows:- class
class_name{}; .
© Oxford University Press 2015. All rights reserved.
Example:- Empty Classes
© Oxford University Press 2015. All rights reserved.
FRIEND FUNCTION
• A friend function of a class is a non-member function of the
class that can access its private and protected members.
• To declare an external function as a friend of the class, you
must include function prototype in the class definition. The
prototype must be preceded with keyword friend.
• The template to use a friend function can be given as follows:
class class_name
{ --------
--------
friend return_type function_name(list of arguments);
© Oxford University Press 2015. All rights reserved.
FRIEND FUNCTION contd.
--------
};
return_type function_name(list of arguments)
{ ---------
---------
}
• Friend function is a normal external function that is given
special access privileges.
• It is defined outside that class’ scope. Therefore, they cannot
be called using the ‘.’ or ‘->’ operator. These operators are
used only when they belong to some class.
© Oxford University Press 2015. All rights reserved.
FRIEND FUNCTION
• While the prototype for friend function is included in the class
definition, it is not considered to be a member function of that
class.
• The friend declaration can be placed either in the private or in
the public section.
• A friend function of the class can be member and friend of
some other class.
• Since friend functions are non-members of the class, they do
not require this pointer. The keyword friend is placed only in
the function declaration and not in the function definition.
• A function can be declared as friend in any number of classes.
• A friend function can access the class’s members using directly
using the object name and dot operator followed by the
specific member.
© Oxford University Press 2015. All rights reserved.
Example:- Friend function
© Oxford University Press 2015. All rights reserved.
FRIEND CLASS
• A friend class is one which can access the private and/or
protected members of another class.
• To declare all members of class A as friends of class B, write
the following
declaration in class A.
friend class B;
© Oxford University Press 2015. All rights reserved.
FRIEND CLASS
• Similar to friend function, a class can be a friend to any
number of classes.
• When we declare a class as friend, then all its members also
become the friend of the other class.
• You must first declare the friend becoming class (forward
declaration).
• A friendship must always be explicitly specified. If class A is a
friend of class B, then class B can access private and protected
members of class B. Since class B is not declared a friend of
class A, class A cannot access private and protected members
of class B.
© Oxford University Press 2015. All rights reserved.
FRIEND CLASS contd.
• A friendship is not transitive. This means that friend of a friend
is not considered a friend unless explicitly specified. For
example, if class A is a friend of class B and class B is a friend
of class C, then it does not imply—unless explicitly
specified—that class A is a friend of class C.
© Oxford University Press 2015. All rights reserved.
BIT-FIELDS IN CLASSES
• It allow users to reserve the exact amount of bits required for
storage of values.
• C++ facilitates users to store integer members into memory
spaces smaller than the compiler would ordinarily allow. These
space-saving members are called bit fields. In addition to this,
C++ permits users to explicitly declare width in bits.
• The syntax for specifying a bit
field can be given as follows:
type:-specifier declarator: constant-expression
© Oxford University Press 2015. All rights reserved.
© Oxford University Press 2015. All rights reserved.
Declaring and Assigning Pointer to Data Members of
a Class
© Oxford University Press 2015. All rights reserved.
Accessing Data Members Using Pointers
© Oxford University Press 2015. All rights reserved.
Pointer to Member Functions
© Oxford University Press 2015. All rights reserved.
Ad

Recommended

Dbms 14: Relational Calculus
Dbms 14: Relational Calculus
Amiya9439793168
 
Register transfer language
Register transfer language
Sanjeev Patel
 
Urban water supply
Urban water supply
Ghassan Hadi
 
Pca analysis
Pca analysis
College of Fisheries, KVAFSU, Mangalore, Karnataka
 
3 classification
3 classification
Mahmoud Alfarra
 
Coefficient of Variance
Coefficient of Variance
Dr. Amjad Ali Arain
 
Digital logic-formula-notes-final-1
Digital logic-formula-notes-final-1
Kshitij Singh
 
Adder & subtractor (Half adder, Full adder, Half subtractor, Full subtractor)
Adder & subtractor (Half adder, Full adder, Half subtractor, Full subtractor)
ISMT College
 
measure of dispersion
measure of dispersion
som allul
 
Women's safety in smart cities
Women's safety in smart cities
GAURAV. H .TANDON
 
INTRODUCTION TO DATABASE
INTRODUCTION TO DATABASE
Muhammad Bilal Tariq
 
Data Preprocessing
Data Preprocessing
Kamal Acharya
 
Chi-square distribution
Chi-square distribution
Habibullah Bahar University College
 
Role of Urban Areas in Biodiversity Conservation
Role of Urban Areas in Biodiversity Conservation
Manoj Neupane
 
K-Folds Cross Validation Method
K-Folds Cross Validation Method
SHUBHAM GUPTA
 
Statistics2x2'x2'yates 'x'2
Statistics2x2'x2'yates 'x'2
Dr. Mangal Kardile
 
Chapter 6 part2-Introduction to Inference-Tests of Significance, Stating Hyp...
Chapter 6 part2-Introduction to Inference-Tests of Significance, Stating Hyp...
nszakir
 
Principal component analysis
Principal component analysis
Partha Sarathi Kar
 
Deterministic vs stochastic
Deterministic vs stochastic
sohail40
 
DBMS NOTES.pdf
DBMS NOTES.pdf
Arivukkarasu Dhanapal
 
Instruction Formats
Instruction Formats
RaaviKapoor
 
DBMS: Types of keys
DBMS: Types of keys
Bharati Ugale
 
8086 signals
8086 signals
mpsrekha83
 
verilog ppt .pdf
verilog ppt .pdf
RavinaBishnoi8
 
BCD,GRAY and EXCESS 3 codes
BCD,GRAY and EXCESS 3 codes
student
 
Minimization of Boolean Functions
Minimization of Boolean Functions
blaircomp2003
 
Measures of Dispersion (Variability)
Measures of Dispersion (Variability)
Sir Parashurambhau College, Pune
 
MACHINE LEARNING LIFE CYCLE
MACHINE LEARNING LIFE CYCLE
Bhimsen Joshi
 
Class and object
Class and object
prabhat kumar
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
manomkpsg
 

More Related Content

What's hot (20)

measure of dispersion
measure of dispersion
som allul
 
Women's safety in smart cities
Women's safety in smart cities
GAURAV. H .TANDON
 
INTRODUCTION TO DATABASE
INTRODUCTION TO DATABASE
Muhammad Bilal Tariq
 
Data Preprocessing
Data Preprocessing
Kamal Acharya
 
Chi-square distribution
Chi-square distribution
Habibullah Bahar University College
 
Role of Urban Areas in Biodiversity Conservation
Role of Urban Areas in Biodiversity Conservation
Manoj Neupane
 
K-Folds Cross Validation Method
K-Folds Cross Validation Method
SHUBHAM GUPTA
 
Statistics2x2'x2'yates 'x'2
Statistics2x2'x2'yates 'x'2
Dr. Mangal Kardile
 
Chapter 6 part2-Introduction to Inference-Tests of Significance, Stating Hyp...
Chapter 6 part2-Introduction to Inference-Tests of Significance, Stating Hyp...
nszakir
 
Principal component analysis
Principal component analysis
Partha Sarathi Kar
 
Deterministic vs stochastic
Deterministic vs stochastic
sohail40
 
DBMS NOTES.pdf
DBMS NOTES.pdf
Arivukkarasu Dhanapal
 
Instruction Formats
Instruction Formats
RaaviKapoor
 
DBMS: Types of keys
DBMS: Types of keys
Bharati Ugale
 
8086 signals
8086 signals
mpsrekha83
 
verilog ppt .pdf
verilog ppt .pdf
RavinaBishnoi8
 
BCD,GRAY and EXCESS 3 codes
BCD,GRAY and EXCESS 3 codes
student
 
Minimization of Boolean Functions
Minimization of Boolean Functions
blaircomp2003
 
Measures of Dispersion (Variability)
Measures of Dispersion (Variability)
Sir Parashurambhau College, Pune
 
MACHINE LEARNING LIFE CYCLE
MACHINE LEARNING LIFE CYCLE
Bhimsen Joshi
 
measure of dispersion
measure of dispersion
som allul
 
Women's safety in smart cities
Women's safety in smart cities
GAURAV. H .TANDON
 
Role of Urban Areas in Biodiversity Conservation
Role of Urban Areas in Biodiversity Conservation
Manoj Neupane
 
K-Folds Cross Validation Method
K-Folds Cross Validation Method
SHUBHAM GUPTA
 
Chapter 6 part2-Introduction to Inference-Tests of Significance, Stating Hyp...
Chapter 6 part2-Introduction to Inference-Tests of Significance, Stating Hyp...
nszakir
 
Deterministic vs stochastic
Deterministic vs stochastic
sohail40
 
Instruction Formats
Instruction Formats
RaaviKapoor
 
BCD,GRAY and EXCESS 3 codes
BCD,GRAY and EXCESS 3 codes
student
 
Minimization of Boolean Functions
Minimization of Boolean Functions
blaircomp2003
 
MACHINE LEARNING LIFE CYCLE
MACHINE LEARNING LIFE CYCLE
Bhimsen Joshi
 

Similar to Introduction to C++ Class & Objects. Book Notes (20)

Class and object
Class and object
prabhat kumar
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
manomkpsg
 
Classes and objects
Classes and objects
Shailendra Veeru
 
Classes and objects
Classes and objects
Anil Kumar
 
oopusingc.pptx
oopusingc.pptx
MohammedAlobaidy16
 
Object oriented programming in C++
Object oriented programming in C++
jehan1987
 
Concept of Object-Oriented in C++
Concept of Object-Oriented in C++
Abdullah Jan
 
Object Oriented Programming Constructors & Destructors
Object Oriented Programming Constructors & Destructors
anitashinde33
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
Lab 4 (1).pdf
Lab 4 (1).pdf
MohammedAlobaidy16
 
Oop objects_classes
Oop objects_classes
sidra tauseef
 
Object and class presentation
Object and class presentation
nafisa rahman
 
Class and object
Class and object
Prof. Dr. K. Adisesha
 
Class object
Class object
Dr. Anand Bihari
 
Implementation of oop concept in c++
Implementation of oop concept in c++
Swarup Boro
 
OOPs & C++ UNIT 3
OOPs & C++ UNIT 3
Dr. SURBHI SAROHA
 
Classes and objects
Classes and objects
Shahid Javid
 
classes & objects.ppt
classes & objects.ppt
BArulmozhi
 
Classes and objects1
Classes and objects1
Vineeta Garg
 
class c++
class c++
vinay chauhan
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
manomkpsg
 
Classes and objects
Classes and objects
Anil Kumar
 
Object oriented programming in C++
Object oriented programming in C++
jehan1987
 
Concept of Object-Oriented in C++
Concept of Object-Oriented in C++
Abdullah Jan
 
Object Oriented Programming Constructors & Destructors
Object Oriented Programming Constructors & Destructors
anitashinde33
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
Object and class presentation
Object and class presentation
nafisa rahman
 
Implementation of oop concept in c++
Implementation of oop concept in c++
Swarup Boro
 
Classes and objects
Classes and objects
Shahid Javid
 
classes & objects.ppt
classes & objects.ppt
BArulmozhi
 
Classes and objects1
Classes and objects1
Vineeta Garg
 
Ad

Recently uploaded (20)

presentation4.pdf Intro to mcmc methodss
presentation4.pdf Intro to mcmc methodss
SergeyTsygankov6
 
Indigo_Airlines_Strategy_Presentation.pptx
Indigo_Airlines_Strategy_Presentation.pptx
mukeshpurohit991
 
Communication_Skills_Class10_Visual.pptx
Communication_Skills_Class10_Visual.pptx
namanrastogi70555
 
Starbucks in the Indian market through its joint venture.
Starbucks in the Indian market through its joint venture.
sales480687
 
最新版美国加利福尼亚大学旧金山法学院毕业证(UCLawSF毕业证书)定制
最新版美国加利福尼亚大学旧金山法学院毕业证(UCLawSF毕业证书)定制
taqyea
 
最新版美国芝加哥大学毕业证(UChicago毕业证书)原版定制
最新版美国芝加哥大学毕业证(UChicago毕业证书)原版定制
taqyea
 
最新版意大利米兰大学毕业证(UNIMI毕业证书)原版定制
最新版意大利米兰大学毕业证(UNIMI毕业证书)原版定制
taqyea
 
All the DataOps, all the paradigms .
All the DataOps, all the paradigms .
Lars Albertsson
 
一比一原版(TUC毕业证书)开姆尼茨工业大学毕业证如何办理
一比一原版(TUC毕业证书)开姆尼茨工业大学毕业证如何办理
taqyed
 
Microsoft Power BI - Advanced Certificate for Business Intelligence using Pow...
Microsoft Power BI - Advanced Certificate for Business Intelligence using Pow...
Prasenjit Debnath
 
Camuflaje Tipos Características Militar 2025.ppt
Camuflaje Tipos Características Militar 2025.ppt
e58650738
 
25 items quiz for practical research 1 in grade 11
25 items quiz for practical research 1 in grade 11
leamaydayaganon81
 
Crafting-Research-Recommendations Grade 12.pptx
Crafting-Research-Recommendations Grade 12.pptx
DaryllWhere
 
@Reset-Password.pptx presentakh;kenvtion
@Reset-Password.pptx presentakh;kenvtion
MarkLariosa1
 
ppt somu_Jarvis_AI_Assistant_presen.pptx
ppt somu_Jarvis_AI_Assistant_presen.pptx
MohammedumarFarhan
 
Measurecamp Copenhagen - Consent Context
Measurecamp Copenhagen - Consent Context
Human37
 
Attendance Presentation Project Excel.pptx
Attendance Presentation Project Excel.pptx
s2025266191
 
624753984-Annex-A3-RPMS-Tool-for-Proficient-Teachers-SY-2024-2025.pdf
624753984-Annex-A3-RPMS-Tool-for-Proficient-Teachers-SY-2024-2025.pdf
CristineGraceAcuyan
 
Indigo dyeing Presentation (2).pptx as dye
Indigo dyeing Presentation (2).pptx as dye
shreeroop1335
 
YEAP !NOT WHAT YOU THINK aakshdjdncnkenfj
YEAP !NOT WHAT YOU THINK aakshdjdncnkenfj
payalmistryb
 
presentation4.pdf Intro to mcmc methodss
presentation4.pdf Intro to mcmc methodss
SergeyTsygankov6
 
Indigo_Airlines_Strategy_Presentation.pptx
Indigo_Airlines_Strategy_Presentation.pptx
mukeshpurohit991
 
Communication_Skills_Class10_Visual.pptx
Communication_Skills_Class10_Visual.pptx
namanrastogi70555
 
Starbucks in the Indian market through its joint venture.
Starbucks in the Indian market through its joint venture.
sales480687
 
最新版美国加利福尼亚大学旧金山法学院毕业证(UCLawSF毕业证书)定制
最新版美国加利福尼亚大学旧金山法学院毕业证(UCLawSF毕业证书)定制
taqyea
 
最新版美国芝加哥大学毕业证(UChicago毕业证书)原版定制
最新版美国芝加哥大学毕业证(UChicago毕业证书)原版定制
taqyea
 
最新版意大利米兰大学毕业证(UNIMI毕业证书)原版定制
最新版意大利米兰大学毕业证(UNIMI毕业证书)原版定制
taqyea
 
All the DataOps, all the paradigms .
All the DataOps, all the paradigms .
Lars Albertsson
 
一比一原版(TUC毕业证书)开姆尼茨工业大学毕业证如何办理
一比一原版(TUC毕业证书)开姆尼茨工业大学毕业证如何办理
taqyed
 
Microsoft Power BI - Advanced Certificate for Business Intelligence using Pow...
Microsoft Power BI - Advanced Certificate for Business Intelligence using Pow...
Prasenjit Debnath
 
Camuflaje Tipos Características Militar 2025.ppt
Camuflaje Tipos Características Militar 2025.ppt
e58650738
 
25 items quiz for practical research 1 in grade 11
25 items quiz for practical research 1 in grade 11
leamaydayaganon81
 
Crafting-Research-Recommendations Grade 12.pptx
Crafting-Research-Recommendations Grade 12.pptx
DaryllWhere
 
@Reset-Password.pptx presentakh;kenvtion
@Reset-Password.pptx presentakh;kenvtion
MarkLariosa1
 
ppt somu_Jarvis_AI_Assistant_presen.pptx
ppt somu_Jarvis_AI_Assistant_presen.pptx
MohammedumarFarhan
 
Measurecamp Copenhagen - Consent Context
Measurecamp Copenhagen - Consent Context
Human37
 
Attendance Presentation Project Excel.pptx
Attendance Presentation Project Excel.pptx
s2025266191
 
624753984-Annex-A3-RPMS-Tool-for-Proficient-Teachers-SY-2024-2025.pdf
624753984-Annex-A3-RPMS-Tool-for-Proficient-Teachers-SY-2024-2025.pdf
CristineGraceAcuyan
 
Indigo dyeing Presentation (2).pptx as dye
Indigo dyeing Presentation (2).pptx as dye
shreeroop1335
 
YEAP !NOT WHAT YOU THINK aakshdjdncnkenfj
YEAP !NOT WHAT YOU THINK aakshdjdncnkenfj
payalmistryb
 
Ad

Introduction to C++ Class & Objects. Book Notes

  • 1. Object Oriented Programming with C++ Reema Thareja © Oxford University Press 2015. All rights reserved.
  • 2. Chapter Nine Classes and Objects © Oxford University Press 2015. All rights reserved.
  • 3. INTRODUCTION © Oxford University Press 2015. All rights reserved. Classes form the building blocks of the object-oriented programming paradigm. They simplify the development of large and complex projects and help produce software which is easy to understand, modular, re-usable, and easily expandable Syntactically, classes are similar to structures, the only difference between a structure and a class is that by default, members of a class are private, while members of a structure are public. Although there is no general rule as when to use a structure and when to use a class, generally, C++ programmers use structures for holding data and classes to hold data and functions.
  • 4. SPECIFYING A CLASS © Oxford University Press 2015. All rights reserved. •A class is the basic mechanism to provide data encapsulation. Data encapsulation is an important feature of object-oriented programming paradigm. •It binds data and member functions in a single entity in such a way that data can be manipulated only through the functions defined in that class. •The process of specifying a class consists of two steps—class declaration and function definitions (Fig.).
  • 5. Class Declaration The keyword class denotes that the class_name that follows is user-defined data type. The body of the class is enclosed within curly braces and terminated with a semicolon, as in structures. Data members and functions are declared within the body of the class. © Oxford University Press 2015. All rights reserved.
  • 6. Visibility Labels • Data and functions are grouped under two sections :-Private and Public data. • Private Data:- All data members and member functions declared private can be accessed only from within the class. • They are strictly not accessible by any entity—function or class—outside the class in which they have been declared. In C++, data hiding is implemented through the private visibility label. • Public Data:- and functions that are public can be accessed from outside the class. • By default, members of the class, both data and function, are private. If any visibility label is missing, they are automatically treated as private members—private and public. © Oxford University Press 2015. All rights reserved.
  • 7. Defining a Function Inside the Class • In this method, function declaration or prototype is replaced with function definition inside the class. • Though it increases the execution speed of the program, it consumes more space. • A function defined inside the class is treated as an inline function by default, provided they do not fall into the restricted category of inline functions. © Oxford University Press 2015. All rights reserved.
  • 8. Example:- Function inside the class © Oxford University Press 2015. All rights reserved.
  • 9. Defining a Function Outside the Class • class_name:: and function_name tell the compiler that scope of the function is restricted to the class_name. The name of the :: operator is scope resolution operator. • The importance of the :: is even more prominent in the following cases. • When different classes in the same program have functions with the same name. In this case,it tells the compiler which function belongs to which class to restrict the non-member functions of the class to use its private members. • It allow a member function of the class to call another member function directly without using the dot operator. © Oxford University Press 2015. All rights reserved.
  • 10. Example:-Defining a function outside the class © Oxford University Press 2015. All rights reserved.
  • 11. CREATING OBJECTS • To use a class, we must create variables of the class also known as objects. • The process of creating objects of the class is called class instantiation. • Memory is allocated only when we create object(s) of the class. • The syntax of defining an object (variable) of a class is as follows:-class_name object_name; . © Oxford University Press 2015. All rights reserved.
  • 12. Example:- Object Creation. © Oxford University Press 2015. All rights reserved.
  • 13. ACCESSING OBJECT MEMBERS • There are two types of class members—private and public. • While private members can be only accessed through public members, public members, on the other hand, can be called from main() or any function outside the class. • The syntax of calling an object member is as follows:- object_name.function_name(arguments); © Oxford University Press 2015. All rights reserved.
  • 14. Example:- Calling of object. © Oxford University Press 2015. All rights reserved.
  • 15. Static Data Members • When a data member is declared as static, the following must be noted:- • Irrespective of the number of objects created, only a single copy of the static member is created in memory. • All objects of a class share the static member. • All static data members are initialized to zero when the first object of that class is created. • Static data members are visible only within the class but their lifetime is the entire program. © Oxford University Press 2015. All rights reserved.
  • 16. Static Data Members • Relevance:-Static data members are usually used to maintain values that are common for the entire class. For example, to keep a track of how many objects of a particular class has been created. • Place of Storage:-Although static data members are declared inside a class, they are not considered to be a part of the objects. Consequently, their declaration in the class is not considered as their defination. A static data member is defined outside the class. This means that even though the static data member is declared in class scope, their defination persist in the entire file. A static member has a file scope. © Oxford University Press 2015. All rights reserved.
  • 17. Static Data Members contd. • However, since a static data member is declared inside the class, they can be accessed only by using the class name and the scope resolution operator. © Oxford University Press 2015. All rights reserved.
  • 18. Example:- Static data members © Oxford University Press 2015. All rights reserved.
  • 19. Static Member Functions • It can access only the static members—data and/or functions—declared in the same class. • It cannot access non-static members because they belong to an object but static functions have no object to work with. • Since it is not a part of any object, it is called using the class name and the scope resolution operator. • As static member functions are not attached to an object, the this pointer does not work on them. • A static member function cannot be declared as virtual function. • A static member function can be declared with const, volatile type qualifiers. © Oxford University Press 2015. All rights reserved.
  • 20. © Oxford University Press 2015. All rights reserved.
  • 21. Static Object • To initialize all the variables of an object to zero, we have two techniques:- • Make a constructor and explicitly set each variable to 0. We will read about it in the next chapter. • To declare the object as static, when an object of a class is declared static, all its members are automatically initialized to zero. © Oxford University Press 2015. All rights reserved.
  • 22. ARRAY OF OBJECTS • Just as we have arrays of basic data types, C++ allows programmers to create arrays of user-defined data types as well. • We can declare an array of class student by simple writing student s[20]; // assuming there are 20 students in a class. • When this statement gets executed, the compiler will set aside memory for storing details of 20 students. • This means that in addition to the space required by member functions, 20 * sizeof(student) bytes of consecutive memory locations will be reserved for objects at the compile time. • An individual object of the array of objects is referenced by using an index, and the particular member is accessed using the dot operator. Therefore, if we write, s[i].get_data() then the statement when executed will take the details of the i th student. © Oxford University Press 2015. All rights reserved.
  • 23. OBJECTS AS FUNCTION ARGUMENTS • Pass-by-value In this technique, a copy of the actual object is created and passed to the called function. • Therefore, the actual (object) and the formal (copy of object) arguments are stored at different memory locations. • This means that any changes made in formal object will not be reflected in the actual object. • Pass-by-reference In this method, the address of the object is implicitly passed to the called function. • Pass-by-address In this technique, the address of the object is explicitly passed to the called function. © Oxford University Press 2015. All rights reserved.
  • 24. © Oxford University Press 2015. All rights reserved. © Oxford University Press 2015. All rights reserved.
  • 25. RETURNING OBJECTS • You can return an object using the following three methods:- • Returning by value which makes a duplicate copy of the local object. • Returning by using a reference to the object. In this way, the address of the object is passed implicitly to the calling function. • Returning by using the ‘this pointer’ which explicitly sends the address of the object to the calling function. © Oxford University Press 2015. All rights reserved.
  • 26. Example:- Returning an object. © Oxford University Press 2015. All rights reserved.
  • 27. this POINTER • C++ uses the this keyword to represent the object that invoked the member function of the class. • this pointer is an implicit parameter to all member functions and can, therefore, be used inside a member function to refer to the invoking object. © Oxford University Press 2015. All rights reserved.
  • 28. © Oxford University Press 2015. All rights reserved.
  • 29. CONSTANT MEMBER FUNCTION • Constant member functions are used when a particular member function should strictly not attempt to change the value of any of the class’s data member. return_type function_name(arguments) const • Note that the keyword const should be suffixed in function header during declaration and defination. © Oxford University Press 2015. All rights reserved.
  • 30. © Oxford University Press 2015. All rights reserved.
  • 31. CONSTANT PARAMETERS • When we pass constant objects as parameters, then members of the object—whether private or public—cannot be changed. • This is even more important when we are passing an object to a non-member function as in, void increment(Employee e, float amt) { e.sal += amt; } • Hence, to prevent any changes by non-member of the class, we must pass the object as a constant object. The function will then receive a read-only copy of the object and will not be allowed to make any changes to it. To pass a const object to the increment function, we must write:- void increment(Employee const e, float amt); void increment(Employee const &e, float amt); © Oxford University Press 2015. All rights reserved.
  • 32. © Oxford University Press 2015. All rights reserved.
  • 33. LOCAL CLASSES • A local class is the class which is defined inside a function. Till now, we were creating global classes since these were defined above all the functions, including main(). • However, as the name implies, a local class is local to the function in which it is defined and therefore is known or accessible only in that function. • There are certain guidelines that must be followed while using local classes, which are as follows:- • Local classes can use any global variable but along with the scope resolution operator. © Oxford University Press 2015. All rights reserved.
  • 34. LOCAL CLASSES • Local classes can use static variables declared inside the function. • Local classes cannot use automatic variables. • Local classes cannot have static data members. • Member functions must be defined inside the class. • Private members of the class cannot be accessed by the enclosing function © Oxford University Press 2015. All rights reserved.
  • 35. © Oxford University Press 2015. All rights reserved.
  • 36. NESTED CLASSES • C++ allows programmers to create a class inside another class. This is called nesting of classes. • When a class B is nested inside another class A, class B is not allowed to access class A’s members. The following points must be noted about nested classes:- • A nested class is declared and defined inside another class. • The scope of the inner class is restricted by the outer class. • While declaring an object of inner class, the name of the inner class must be preceded with the name of the outer class. © Oxford University Press 2015. All rights reserved.
  • 37. © Oxford University Press 2015. All rights reserved.
  • 38. COMPLEX OBJECTS ( OBJECT COMPOSITION) • Complex objects are objects that are built from smaller or simpler objects • In OOP, it is used for objects that have a has-a relationship to each other. For ex, a car has-a metal frame, has-an engine, etc. • Benefits • Each individual class can be simple and straightforward. • A class can focus on performing one specific task. • The class is easier to write, debug, understand, and usable by other programmers. © Oxford University Press 2015. All rights reserved.
  • 39. COMPLEX OBJECTS ( OBJECT COMPOSITION) • While simpler classes can perform all the operations, the complex class can be designed to coordinate the data flow between simpler classes. • It lowers the overall complexity of the complex object because the main task of the complex object would then be to delegate tasks to the sub-objects, who already know how to do them. © Oxford University Press 2015. All rights reserved.
  • 40. © Oxford University Press 2015. All rights reserved.
  • 41. EMPTY CLASSES • An empty class is one in which there are no data members and no member functions. These type of classes are not frequently used. However, at times, they may be used for exception handling, discussed in a later chapter. • The syntax of defining an empty class is as follows:- class class_name{}; . © Oxford University Press 2015. All rights reserved.
  • 42. Example:- Empty Classes © Oxford University Press 2015. All rights reserved.
  • 43. FRIEND FUNCTION • A friend function of a class is a non-member function of the class that can access its private and protected members. • To declare an external function as a friend of the class, you must include function prototype in the class definition. The prototype must be preceded with keyword friend. • The template to use a friend function can be given as follows: class class_name { -------- -------- friend return_type function_name(list of arguments); © Oxford University Press 2015. All rights reserved.
  • 44. FRIEND FUNCTION contd. -------- }; return_type function_name(list of arguments) { --------- --------- } • Friend function is a normal external function that is given special access privileges. • It is defined outside that class’ scope. Therefore, they cannot be called using the ‘.’ or ‘->’ operator. These operators are used only when they belong to some class. © Oxford University Press 2015. All rights reserved.
  • 45. FRIEND FUNCTION • While the prototype for friend function is included in the class definition, it is not considered to be a member function of that class. • The friend declaration can be placed either in the private or in the public section. • A friend function of the class can be member and friend of some other class. • Since friend functions are non-members of the class, they do not require this pointer. The keyword friend is placed only in the function declaration and not in the function definition. • A function can be declared as friend in any number of classes. • A friend function can access the class’s members using directly using the object name and dot operator followed by the specific member. © Oxford University Press 2015. All rights reserved.
  • 46. Example:- Friend function © Oxford University Press 2015. All rights reserved.
  • 47. FRIEND CLASS • A friend class is one which can access the private and/or protected members of another class. • To declare all members of class A as friends of class B, write the following declaration in class A. friend class B; © Oxford University Press 2015. All rights reserved.
  • 48. FRIEND CLASS • Similar to friend function, a class can be a friend to any number of classes. • When we declare a class as friend, then all its members also become the friend of the other class. • You must first declare the friend becoming class (forward declaration). • A friendship must always be explicitly specified. If class A is a friend of class B, then class B can access private and protected members of class B. Since class B is not declared a friend of class A, class A cannot access private and protected members of class B. © Oxford University Press 2015. All rights reserved.
  • 49. FRIEND CLASS contd. • A friendship is not transitive. This means that friend of a friend is not considered a friend unless explicitly specified. For example, if class A is a friend of class B and class B is a friend of class C, then it does not imply—unless explicitly specified—that class A is a friend of class C. © Oxford University Press 2015. All rights reserved.
  • 50. BIT-FIELDS IN CLASSES • It allow users to reserve the exact amount of bits required for storage of values. • C++ facilitates users to store integer members into memory spaces smaller than the compiler would ordinarily allow. These space-saving members are called bit fields. In addition to this, C++ permits users to explicitly declare width in bits. • The syntax for specifying a bit field can be given as follows: type:-specifier declarator: constant-expression © Oxford University Press 2015. All rights reserved.
  • 51. © Oxford University Press 2015. All rights reserved.
  • 52. Declaring and Assigning Pointer to Data Members of a Class © Oxford University Press 2015. All rights reserved.
  • 53. Accessing Data Members Using Pointers © Oxford University Press 2015. All rights reserved.
  • 54. Pointer to Member Functions © Oxford University Press 2015. All rights reserved.