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

More Related Content

What's hot (20)

Method overriding
Method overridingMethod overriding
Method overriding
Azaz Maverick
 
Left recursion
Left recursionLeft recursion
Left recursion
Farzana Aktar
 
Flow control main
Flow control mainFlow control main
Flow control main
Nitesh Singh
 
Electronic mail protocols and operations
 Electronic mail protocols and operations Electronic mail protocols and operations
Electronic mail protocols and operations
VivekRajawat9
 
Storage management
Storage managementStorage management
Storage management
Atul Sharma
 
System call
System callSystem call
System call
DarakhshanNayyab
 
Informatics Practices Chapter 2 Open Source Software Concepts Class 12th
 Informatics Practices Chapter 2  Open Source Software Concepts Class 12th Informatics Practices Chapter 2  Open Source Software Concepts Class 12th
Informatics Practices Chapter 2 Open Source Software Concepts Class 12th
Harsh Mathur
 
TCP/ IP
TCP/ IP TCP/ IP
TCP/ IP
Harshit Srivastava
 
OS Unit 5 - Memory Management
OS Unit 5 - Memory ManagementOS Unit 5 - Memory Management
OS Unit 5 - Memory Management
Gyanmanjari Institute Of Technology
 
Computer Network Components
Computer Network  ComponentsComputer Network  Components
Computer Network Components
Jyoti Akhter
 
Device security master (ASA Firewall) - project thesis - SZABIST-ZABTech Hyde...
Device security master (ASA Firewall) - project thesis - SZABIST-ZABTech Hyde...Device security master (ASA Firewall) - project thesis - SZABIST-ZABTech Hyde...
Device security master (ASA Firewall) - project thesis - SZABIST-ZABTech Hyde...
MehtabRohela
 
Internet protocol stack
Internet protocol stackInternet protocol stack
Internet protocol stack
Ami Prakash
 
POP3 Post Office Protocol
POP3 Post Office ProtocolPOP3 Post Office Protocol
POP3 Post Office Protocol
Samreen Reyaz Ansari
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
Tareq Hasan
 
Generic types and collections GUIs.pptx
Generic types and collections GUIs.pptxGeneric types and collections GUIs.pptx
Generic types and collections GUIs.pptx
Avirup Pal
 
2. microkernel new
2. microkernel new2. microkernel new
2. microkernel new
AbDul ThaYyal
 
Power point presentation on access specifier in OOPs
Power point presentation on access specifier in OOPsPower point presentation on access specifier in OOPs
Power point presentation on access specifier in OOPs
AdrizaBera
 
Generalization and specialization
Generalization and specializationGeneralization and specialization
Generalization and specialization
Knowledge Center Computer
 
difference between hub, bridge, switch and router
difference between hub, bridge, switch and routerdifference between hub, bridge, switch and router
difference between hub, bridge, switch and router
Akmal Cikmat
 
Object Oriented Programming Concepts for beginners
Object Oriented Programming Concepts for beginners Object Oriented Programming Concepts for beginners
Object Oriented Programming Concepts for beginners
Vibhawa Nirmal
 
Electronic mail protocols and operations
 Electronic mail protocols and operations Electronic mail protocols and operations
Electronic mail protocols and operations
VivekRajawat9
 
Storage management
Storage managementStorage management
Storage management
Atul Sharma
 
Informatics Practices Chapter 2 Open Source Software Concepts Class 12th
 Informatics Practices Chapter 2  Open Source Software Concepts Class 12th Informatics Practices Chapter 2  Open Source Software Concepts Class 12th
Informatics Practices Chapter 2 Open Source Software Concepts Class 12th
Harsh Mathur
 
Computer Network Components
Computer Network  ComponentsComputer Network  Components
Computer Network Components
Jyoti Akhter
 
Device security master (ASA Firewall) - project thesis - SZABIST-ZABTech Hyde...
Device security master (ASA Firewall) - project thesis - SZABIST-ZABTech Hyde...Device security master (ASA Firewall) - project thesis - SZABIST-ZABTech Hyde...
Device security master (ASA Firewall) - project thesis - SZABIST-ZABTech Hyde...
MehtabRohela
 
Internet protocol stack
Internet protocol stackInternet protocol stack
Internet protocol stack
Ami Prakash
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
Tareq Hasan
 
Generic types and collections GUIs.pptx
Generic types and collections GUIs.pptxGeneric types and collections GUIs.pptx
Generic types and collections GUIs.pptx
Avirup Pal
 
Power point presentation on access specifier in OOPs
Power point presentation on access specifier in OOPsPower point presentation on access specifier in OOPs
Power point presentation on access specifier in OOPs
AdrizaBera
 
difference between hub, bridge, switch and router
difference between hub, bridge, switch and routerdifference between hub, bridge, switch and router
difference between hub, bridge, switch and router
Akmal Cikmat
 
Object Oriented Programming Concepts for beginners
Object Oriented Programming Concepts for beginners Object Oriented Programming Concepts for beginners
Object Oriented Programming Concepts for beginners
Vibhawa Nirmal
 

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

C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
Dennis Chang
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
Getachew Ganfur
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
baabtra.com - No. 1 supplier of quality freshers
 
APL-2-classes and objects.ppt data structures using c++
APL-2-classes and objects.ppt data structures using c++APL-2-classes and objects.ppt data structures using c++
APL-2-classes and objects.ppt data structures using c++
ProfLSrividya
 
APL-2-classes and objects.ppt
APL-2-classes and objects.pptAPL-2-classes and objects.ppt
APL-2-classes and objects.ppt
srividyal2
 
Concept of Object-Oriented in C++
Concept of Object-Oriented in C++Concept of Object-Oriented in C++
Concept of Object-Oriented in C++
Abdullah Jan
 
object oriented programing lecture 1
object oriented programing lecture 1object oriented programing lecture 1
object oriented programing lecture 1
Geophery sanga
 
oopm 2.pdf
oopm 2.pdfoopm 2.pdf
oopm 2.pdf
jayeshsoni49
 
OOP Presentation.pptx
OOP Presentation.pptxOOP Presentation.pptx
OOP Presentation.pptx
DurgaPrasadVasantati
 
OOP Presentation.pptx
OOP Presentation.pptxOOP Presentation.pptx
OOP Presentation.pptx
DurgaPrasadVasantati
 
C++ training
C++ training C++ training
C++ training
PL Sharma
 
Lesson 13 object and class
Lesson 13 object and classLesson 13 object and class
Lesson 13 object and class
MLG College of Learning, Inc
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
Shailendra Veeru
 
c++.pptxwjwjsijsnsksomammaoansnksooskskk
c++.pptxwjwjsijsnsksomammaoansnksooskskkc++.pptxwjwjsijsnsksomammaoansnksooskskk
c++.pptxwjwjsijsnsksomammaoansnksooskskk
mitivete
 
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas AghaniC# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
Information Technology Center
 
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas AghaniC# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
Information Technology Center
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Object
dkpawar
 
Advanced Topics on Database - Unit-2 AU17
Advanced Topics on Database - Unit-2 AU17Advanced Topics on Database - Unit-2 AU17
Advanced Topics on Database - Unit-2 AU17
LOGANATHANK24
 
1_Object Oriented Programming.pptx
1_Object Oriented Programming.pptx1_Object Oriented Programming.pptx
1_Object Oriented Programming.pptx
umarAnjum6
 
Summer Training Project On C++
Summer Training Project On  C++Summer Training Project On  C++
Summer Training Project On C++
KAUSHAL KUMAR JHA
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
Dennis Chang
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
Getachew Ganfur
 
APL-2-classes and objects.ppt data structures using c++
APL-2-classes and objects.ppt data structures using c++APL-2-classes and objects.ppt data structures using c++
APL-2-classes and objects.ppt data structures using c++
ProfLSrividya
 
APL-2-classes and objects.ppt
APL-2-classes and objects.pptAPL-2-classes and objects.ppt
APL-2-classes and objects.ppt
srividyal2
 
Concept of Object-Oriented in C++
Concept of Object-Oriented in C++Concept of Object-Oriented in C++
Concept of Object-Oriented in C++
Abdullah Jan
 
object oriented programing lecture 1
object oriented programing lecture 1object oriented programing lecture 1
object oriented programing lecture 1
Geophery sanga
 
C++ training
C++ training C++ training
C++ training
PL Sharma
 
c++.pptxwjwjsijsnsksomammaoansnksooskskk
c++.pptxwjwjsijsnsksomammaoansnksooskskkc++.pptxwjwjsijsnsksomammaoansnksooskskk
c++.pptxwjwjsijsnsksomammaoansnksooskskk
mitivete
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Object
dkpawar
 
Advanced Topics on Database - Unit-2 AU17
Advanced Topics on Database - Unit-2 AU17Advanced Topics on Database - Unit-2 AU17
Advanced Topics on Database - Unit-2 AU17
LOGANATHANK24
 
1_Object Oriented Programming.pptx
1_Object Oriented Programming.pptx1_Object Oriented Programming.pptx
1_Object Oriented Programming.pptx
umarAnjum6
 
Summer Training Project On C++
Summer Training Project On  C++Summer Training Project On  C++
Summer Training Project On C++
KAUSHAL KUMAR JHA
 
Ad

Recently uploaded (20)

HershAggregator (2).pdf musicretaildistribution
HershAggregator (2).pdf musicretaildistributionHershAggregator (2).pdf musicretaildistribution
HershAggregator (2).pdf musicretaildistribution
hershtara1
 
Time series for yotube_1_data anlysis.pdf
Time series for yotube_1_data anlysis.pdfTime series for yotube_1_data anlysis.pdf
Time series for yotube_1_data anlysis.pdf
asmaamahmoudsaeed
 
Fundamentals of Data Analysis, its types, tools, algorithms
Fundamentals of Data Analysis, its types, tools, algorithmsFundamentals of Data Analysis, its types, tools, algorithms
Fundamentals of Data Analysis, its types, tools, algorithms
priyaiyerkbcsc
 
problem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursingproblem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursing
vishnudathas123
 
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
disnakertransjabarda
 
Automation Platforms and Process Mining - success story
Automation Platforms and Process Mining - success storyAutomation Platforms and Process Mining - success story
Automation Platforms and Process Mining - success story
Process mining Evangelist
 
Multi-tenant Data Pipeline Orchestration
Multi-tenant Data Pipeline OrchestrationMulti-tenant Data Pipeline Orchestration
Multi-tenant Data Pipeline Orchestration
Romi Kuntsman
 
RAG Chatbot using AWS Bedrock and Streamlit Framework
RAG Chatbot using AWS Bedrock and Streamlit FrameworkRAG Chatbot using AWS Bedrock and Streamlit Framework
RAG Chatbot using AWS Bedrock and Streamlit Framework
apanneer
 
What is ETL? Difference between ETL and ELT?.pdf
What is ETL? Difference between ETL and ELT?.pdfWhat is ETL? Difference between ETL and ELT?.pdf
What is ETL? Difference between ETL and ELT?.pdf
SaikatBasu37
 
Understanding Complex Development Processes
Understanding Complex Development ProcessesUnderstanding Complex Development Processes
Understanding Complex Development Processes
Process mining Evangelist
 
lecture_13 tree in mmmmmmmm mmmmmfftro.pptx
lecture_13 tree in mmmmmmmm     mmmmmfftro.pptxlecture_13 tree in mmmmmmmm     mmmmmfftro.pptx
lecture_13 tree in mmmmmmmm mmmmmfftro.pptx
sarajafffri058
 
Dynamics 365 Business Rules Dynamics Dynamics
Dynamics 365 Business Rules Dynamics DynamicsDynamics 365 Business Rules Dynamics Dynamics
Dynamics 365 Business Rules Dynamics Dynamics
heyoubro69
 
Automated Melanoma Detection via Image Processing.pptx
Automated Melanoma Detection via Image Processing.pptxAutomated Melanoma Detection via Image Processing.pptx
Automated Melanoma Detection via Image Processing.pptx
handrymaharjan23
 
TOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdf
TOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdfTOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdf
TOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdf
NhiV747372
 
Lesson 6-Interviewing in SHRM_updated.pdf
Lesson 6-Interviewing in SHRM_updated.pdfLesson 6-Interviewing in SHRM_updated.pdf
Lesson 6-Interviewing in SHRM_updated.pdf
hemelali11
 
How to Set Up Process Mining in a Decentralized Organization?
How to Set Up Process Mining in a Decentralized Organization?How to Set Up Process Mining in a Decentralized Organization?
How to Set Up Process Mining in a Decentralized Organization?
Process mining Evangelist
 
AWS Certified Machine Learning Slides.pdf
AWS Certified Machine Learning Slides.pdfAWS Certified Machine Learning Slides.pdf
AWS Certified Machine Learning Slides.pdf
philsparkshome
 
hersh's midterm project.pdf music retail and distribution
hersh's midterm project.pdf music retail and distributionhersh's midterm project.pdf music retail and distribution
hersh's midterm project.pdf music retail and distribution
hershtara1
 
Lagos School of Programming Final Project Updated.pdf
Lagos School of Programming Final Project Updated.pdfLagos School of Programming Final Project Updated.pdf
Lagos School of Programming Final Project Updated.pdf
benuju2016
 
Z14_IBM__APL_by_Christian_Demmer_IBM.pdf
Z14_IBM__APL_by_Christian_Demmer_IBM.pdfZ14_IBM__APL_by_Christian_Demmer_IBM.pdf
Z14_IBM__APL_by_Christian_Demmer_IBM.pdf
Fariborz Seyedloo
 
HershAggregator (2).pdf musicretaildistribution
HershAggregator (2).pdf musicretaildistributionHershAggregator (2).pdf musicretaildistribution
HershAggregator (2).pdf musicretaildistribution
hershtara1
 
Time series for yotube_1_data anlysis.pdf
Time series for yotube_1_data anlysis.pdfTime series for yotube_1_data anlysis.pdf
Time series for yotube_1_data anlysis.pdf
asmaamahmoudsaeed
 
Fundamentals of Data Analysis, its types, tools, algorithms
Fundamentals of Data Analysis, its types, tools, algorithmsFundamentals of Data Analysis, its types, tools, algorithms
Fundamentals of Data Analysis, its types, tools, algorithms
priyaiyerkbcsc
 
problem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursingproblem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursing
vishnudathas123
 
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
disnakertransjabarda
 
Automation Platforms and Process Mining - success story
Automation Platforms and Process Mining - success storyAutomation Platforms and Process Mining - success story
Automation Platforms and Process Mining - success story
Process mining Evangelist
 
Multi-tenant Data Pipeline Orchestration
Multi-tenant Data Pipeline OrchestrationMulti-tenant Data Pipeline Orchestration
Multi-tenant Data Pipeline Orchestration
Romi Kuntsman
 
RAG Chatbot using AWS Bedrock and Streamlit Framework
RAG Chatbot using AWS Bedrock and Streamlit FrameworkRAG Chatbot using AWS Bedrock and Streamlit Framework
RAG Chatbot using AWS Bedrock and Streamlit Framework
apanneer
 
What is ETL? Difference between ETL and ELT?.pdf
What is ETL? Difference between ETL and ELT?.pdfWhat is ETL? Difference between ETL and ELT?.pdf
What is ETL? Difference between ETL and ELT?.pdf
SaikatBasu37
 
lecture_13 tree in mmmmmmmm mmmmmfftro.pptx
lecture_13 tree in mmmmmmmm     mmmmmfftro.pptxlecture_13 tree in mmmmmmmm     mmmmmfftro.pptx
lecture_13 tree in mmmmmmmm mmmmmfftro.pptx
sarajafffri058
 
Dynamics 365 Business Rules Dynamics Dynamics
Dynamics 365 Business Rules Dynamics DynamicsDynamics 365 Business Rules Dynamics Dynamics
Dynamics 365 Business Rules Dynamics Dynamics
heyoubro69
 
Automated Melanoma Detection via Image Processing.pptx
Automated Melanoma Detection via Image Processing.pptxAutomated Melanoma Detection via Image Processing.pptx
Automated Melanoma Detection via Image Processing.pptx
handrymaharjan23
 
TOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdf
TOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdfTOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdf
TOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdf
NhiV747372
 
Lesson 6-Interviewing in SHRM_updated.pdf
Lesson 6-Interviewing in SHRM_updated.pdfLesson 6-Interviewing in SHRM_updated.pdf
Lesson 6-Interviewing in SHRM_updated.pdf
hemelali11
 
How to Set Up Process Mining in a Decentralized Organization?
How to Set Up Process Mining in a Decentralized Organization?How to Set Up Process Mining in a Decentralized Organization?
How to Set Up Process Mining in a Decentralized Organization?
Process mining Evangelist
 
AWS Certified Machine Learning Slides.pdf
AWS Certified Machine Learning Slides.pdfAWS Certified Machine Learning Slides.pdf
AWS Certified Machine Learning Slides.pdf
philsparkshome
 
hersh's midterm project.pdf music retail and distribution
hersh's midterm project.pdf music retail and distributionhersh's midterm project.pdf music retail and distribution
hersh's midterm project.pdf music retail and distribution
hershtara1
 
Lagos School of Programming Final Project Updated.pdf
Lagos School of Programming Final Project Updated.pdfLagos School of Programming Final Project Updated.pdf
Lagos School of Programming Final Project Updated.pdf
benuju2016
 
Z14_IBM__APL_by_Christian_Demmer_IBM.pdf
Z14_IBM__APL_by_Christian_Demmer_IBM.pdfZ14_IBM__APL_by_Christian_Demmer_IBM.pdf
Z14_IBM__APL_by_Christian_Demmer_IBM.pdf
Fariborz Seyedloo
 
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.
  翻译: