SlideShare a Scribd company logo
1 of 49
WEL COME
PRAVEEN M JIGAJINNI
PGT (Computer Science)
MTech[IT],MPhil (Comp.Sci), MCA, MSc[IT], PGDCA, ADCA,
Dc. Sc. & Engg.
email: praveenkumarjigajinni@yahoo.co.in
CHAPTER 4
Classes & Objects
What is Class?
The mechanism that allows you to combine
data and the function in a single unit is called a
class. Once a class is defined, you can
declare variables of that type. A class variable
is called object or instance. In other words, a
class would be the data type, and an object
would be the variable. Classes are generally
declared using the keyword class.
What is Class?
A class is the collection of related data and
function under a single name. A C++ program
can have any number of classes. When
related data and functions are kept under a
class, it helps to visualize the complex
problem efficiently and effectively.
What is Class?
A class is a definition of an object. It's
a type just like int . A class resembles
a struct with just one difference : all struct
members are public by default. All classes
members are private.
Objects are the biggest difference between C+
+ and C . One of the earliest names for C++
was C with Classes.
Remember : A class is a type, and an object of
this class is just a variable.
What is Class?
A class is a user defined type or data structure
declared with keyword class that has data and
functions (also called methods) as its members
whose access is governed by the three access
specifiers private, protected or public (by default
access to members of a class is private). A
class (declared with keyword class) in C++
differs from a structure (declared with
keyword struct) as by default, members
are private in a class while they are public in a
structure.
What is Class?
The private members are not accessible outside
the class; they can be accessed only through
methods of the class. The public members form
an interface to the class and are accessible
outside the class. Instances of these data types
are known as objects and can contain member
variables, constants, member functions,
and overloaded operators defined by the
programmer.
Defining Class
class class_name
{
Data Members; Methods;
};
OR
class class_name
{
private: members1;
protected: members2;
public: members3;
};
Defining Class
Where class_name is a valid identifier for the
class. The body of the declaration can contain
members, that can be either data or function
declarations, The members of a class are
classified into three categories: private, public,
and protected. private, protected, and public
are reserved words and are called member
access specifies. These specifies modify the
access rights that the members following them
acquire.
Defining Class
private members of a class are accessible only
from within other members of the same class. You
cannot access it outside of the class.
protected members are accessible from
members of their same class and also from
members of their derived classes.
protected members are accessible from other
members of the same class (or from
their "friends"), but also from members of their
derived classes.
Defining Class
Finally, public members are accessible from
anywhere where the object is visible.
By default, all members of a class declared with
the class keyword have private access for all its
members. Therefore, any member that is declared
before one other class specifies automatically has
private access.
Defining Class
Example
class Circle
{
private: double radius;
public: void setRadius(double r)
{ radius = r; }
double getArea()
{ return 3.14 * radius * radius; }
};
Defining Member Function of Class
Member functions can be defined in two ways,
1.Inside the class
2.Outside the class
Defining Member Function of Class
1.Inside the class
You can define Functions inside the class as shown in
previous slides. Member functions defined inside a class
this way are created as inline functions by default. It is also
possible to declare a function within a class but define it
elsewhere. Functions defined outside the class are not
normally inline.
When we define a function outside the class we cannot
reference them (directly) outside of the class. In order to
reference these, we use the scope resolution operator, ::
(double colon). In this example, we are defining function
setRadius outside the class:
Defining Member Function of Class
2. Outside the class
A large program may contain many member
functions. For the clarity of the code, member
functions can be defined outside the class. To do
so, member function should be declared inside the
class(function prototype should be inside the
class). Then, the function definition can be defined
using scope resolution operator ::.
Defining Member Function of Class
2. Outside the class
When we define a function outside the class we
cannot reference them (directly) outside of the
class. In order to reference these, we use the
scope resolution operator, :: (double colon). In this
example, we are defining function setRadius
outside the class:
void Circle :: setRadius(double r) { radius = r; }
Object Declaration
Once a class is defined, you can declare objects of
that type. The syntax for declaring a object is the
same as that for declaring any other variable. The
following statements declare two objects of type
circle:
Circle c1, c2;
Circle is class and c1 and c2 are the objects.
Once the class is defined you can define any
number of objects.
Object Declaration
Accessing Class Members
Once an object of a class is declared, it can
access the public members of the class using ( . )
dot membership operator.
c1.setRadius(2.5);
Arrays within Class
The array can be used as member variables in a
class. The following class definition is valid.
const int size=10;
class array
{
int a[size];
public:
void setval(void);
void display(void);
};
Arrays within Class
The array variable a[] declared as private member
of the class array can be used in the member
function, like any other array variable. We can
perform any operations on it. For instance, in the
above class definition, the member function
setval() sets the value of element of the array a[],
and display() function displays the values.
Similarly, we may use other member functions to
perform any other operation on the array values.
Access modifiers
Access modifiers (or access specifiers)
are keywords in object-oriented languages that set
the accessibility of classes, methods, and other
members. Access modifiers are a specific part of
programming language syntax used to facilitate
the encapsulation of components
Access modifiers
In C++, there are only three access
modifiers. C# extends the number of them to five,
while Java has four access modifiers,[2]
but three
keywords for this purpose. In Java, having no
keyword before defaults to the package-private
modifier. Access specifiers for classes:- When a
class is declared as public, it is accessible to other
classes defined in the same package as well as
those defined in other packages. This is the most
commonly used specifier for classes.
Access modifiers
A class cannot be declared as private. If no access
specifier is stated, the default access restrictions
will be applied. The class will be accessible to
other classes in the same package but will be
inaccessible to classes outside the package. When
we say that a class is inaccessible, it simply
means that we cannot create an object of that
class or declare a variable of that class type. The
protected access specifier too cannot be applied to
a class.
Access modifiers
C++ uses the three modifiers
called public, protected, and private.
C# has the modifiers public, protected ,
internal, private, and protected internal.
Java has public, package, protected, and private.
Local Classes in C++
A class declared inside a function becomes local to
that function and is called Local Class in C++.
For example, in the following program, Test is a
local class in fun().
void fun()
{
class Test // local to fun
{
/* members of Test class */
};
}
Global Classes in C++
A class declared outside the body of all the function
in a program is called Global Class in C++.
For example
class sample
{ int x; public: void readx() { cin>>x;} };
void main()
{
sample s1;
s1.readx();
}
Local and Global Objects in C++
A class declared outside the body of all the function
in a program is called Global Class in C++.
For example
class sample
{ int x; public: void readx() { cin>>x;} };
sample s1; // Global Object
void main()
{
sample s2; // Local Object
s1.readx();
}
STATIC FUNCTION MEMBERS
• We can define class members static using static
keyword. When we declare a member of a class as static
it means no matter how many objects of the class are
created, there is only one copy of the static member.
• A static member is shared by all objects of the class. All
static data is initialized to zero when the first object is
created, if no other initialization is present. We can't put it
in the class definition but it can be initialized outside the
class as done in the following example by redeclaring
the static variable, using the scope resolution operator ::
to identify which class it belongs to.
STATIC FUNCTION MEMBERS
• By declaring a function member as static, you make it
independent of any particular object of the class. A static
member function can be called even if no objects of the
class exist and the static functions are accessed using
only the class name and the scope resolution operator ::.
• A static member function can only access static data
member, other static member functions and any other
functions from outside the class.
• Static member functions have a class scope and they do
not have access to the this pointer of the class. You
could use a static member function to determine whether
some objects of the class have been created or not.
class test
{
static int i;
public: void static geti() { ++i; }
void printi() { cout<<"n i val is = "<<i; }
};
int test :: i=0; // needs to be initilized.
void main()
{
clrscr();
test t1, t2;
t1.geti();
t2.geti();
t1.printi();
getch();
}
What is C++ inline functions
In C, we have used Macro function an optimized
technique used by compiler to reduce the execution
time etc. So Question comes in mind that what’s
there in C++ for that and in what all better ways?
Inline function is introduced which is an optimization
technique used by the compilers especially to
reduce the execution time. We will cover “what, why,
when & how” of inline functions.
What is C++ inline functions
The inline functions are a C++ enhancement feature to
increase the execution time of a program. Functions can
be instructed to compiler to make them inline so that
compiler can replace those function definition wherever
those are being called. Compiler replaces the definition
of inline functions at compile time instead of referring
function definition at runtime. Inline functions are defined
with inline keyword. For Example:
inline int sqr(int x)
{
int y;
y = x * x;
return y; }
What is C++ inline functions
Pros :-
1. It speeds up your program by avoiding function
calling overhead.
2. It save overhead of variables push/pop on the
stack, when function calling happens.
3. It save overhead of return call from a function.
4. It increases locality of reference by utilizing
instruction cache.
What is C++ inline functions
Pros
5. By marking it as inline, you can put a function
definition in a header file (i.e. it can be included in
multiple compilation unit, without the linker
complaining)
What is C++ inline functions
Cons :-
1. It increases the executable size due to code
expansion.
2. C++ inlining is resolved at compile time. Which
means if you change the code of the inlined
function, you would need to recompile all the code
using it to make sure it will be updated.
3. When used in a header, it makes your header file
larger with information which users don’t care.
What is C++ inline functions
Cons :-
4. As mentioned above it increases the executable
size, which may cause thrashing in memory. More
number of page fault bringing down your program
performance.
5. Sometimes not useful for example in embedded
system where large executable size is not preferred
at all due to memory constraints.
When inline functions do not work?
The function should be inlined only when they are
small. There is no point in inlining large functions as
there would be heavy memory penalty. The linlining
does not work for the following situations.
1.For a functions that returns the values and are
having a loop or a switch or goto statements.
2.For a functions not returning values, if return
statement exists.
3.If a functions contain static variables.
4.If the function is recursive.
FRIEND FUNCTION
A friend function is a function that is not a
member of a class but has access to the class's
private and protected members. Friend functions
are not considered class members; they are normal
external functions that are given special access
privileges.
To declare a function as a friend of a class, precede
the function prototype in the class definition with
keyword friend as follows:
FRIEND FUNCTION
Friend functions have the following properties:
1)Friend of the class can be member of some other
class.
2) Friend of one class can be friend of another class
or all the classes in one program, such a friend is
known as GLOBAL FRIEND.
3) Friend can access the private or protected
members of the class in which they are declared to
be friend, but they can use the members for a
specific object.
FRIEND FUNCTION
Friend functions have the following properties:
4) Friends are non-members hence do not get “this”
pointer.
5) Friends, can be friend of more than one class,
hence they can be used for message passing
between the classes.
6) Friend can be declared anywhere (in public,
protected or private section) in the class.
FRIEND FUNCTION – AN EXAMPLE
class base
{
int val1,val2;
public:
void get()
{
cout<<"Enter two values:";
cin>>val1>>val2;
}
friend float mean(base ob);
};
FRIEND FUNCTION – AN EXAMPLE
float mean(base ob)
{
return float(ob.val1+ob.val2)/2;
}
void main()
{
clrscr();
base obj;
obj.get();
cout<<"n Mean value is : "<<mean(obj);
getch();
}
FRIEND CLASS
A class can also be declared to be the friend of
some other class. When we create a friend class
then all the member functions of the friend class
also become the friend of the other class. This
requires the condition that the friend becoming class
must be first declared or defined (forward
declaration).
FRIEND CLASS
class MyClass
{
friend class SecondClass; // Declare a friend class
public: MyClass() : Secret(0){}
void printMember()
{ cout << Secret << endl; }
private: int Secret;
};
FRIEND CLASS
class SecondClass
{
public: void change( MyClass& yourclass, int x )
{ yourclass.Secret = x; }
};
FRIEND CLASS
void main()
{
MyClass my_class;
SecondClass sec_class;
my_class.printMember();
sec_class.change(my_class,5);
my_class.printMember();
}
Note: we declared friend class SecondClass; in the
class MyClass, so we can access Secret in the
class SecondClass.
Contd…
FRIEND CLASS
Another property of friendships is that they are not
transitive: The friend of a friend is not considered to
be a friend unless explicitly specified.
?Any Questions Please
Thank You
Very Much

More Related Content

What's hot

Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Classes and objects till 16 aug
Classes and objects till 16 augClasses and objects till 16 aug
Classes and objects till 16 augshashank12march
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingSyed Faizan Hassan
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functionsMarlom46
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++Muhammad Waqas
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classesFajar Baskoro
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introductionSohanur63
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in javaAtul Sehdev
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Majid Saeed
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++NainaKhan28
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objectsmaznabili
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan collegeahmed hmed
 
Functions, classes & objects in c++
Functions, classes & objects in c++Functions, classes & objects in c++
Functions, classes & objects in c++ThamizhselviKrishnam
 

What's hot (20)

Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Classes and objects till 16 aug
Classes and objects till 16 augClasses and objects till 16 aug
Classes and objects till 16 aug
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programming
 
Object and class
Object and classObject and class
Object and class
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in java
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
C++ classes
C++ classesC++ classes
C++ classes
 
Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan college
 
Functions, classes & objects in c++
Functions, classes & objects in c++Functions, classes & objects in c++
Functions, classes & objects in c++
 

Viewers also liked

Lecciones aprendidas en otros contextos
Lecciones aprendidas en otros contextosLecciones aprendidas en otros contextos
Lecciones aprendidas en otros contextosGerardo
 
Uni papua fc landak unit mempawah hulu doing excersice
Uni papua fc landak unit mempawah hulu doing excersiceUni papua fc landak unit mempawah hulu doing excersice
Uni papua fc landak unit mempawah hulu doing excersiceUni Papua Football
 
Marketing Case Studies
Marketing Case StudiesMarketing Case Studies
Marketing Case StudiesNextBee Media
 
UDI interdisciplinar IES Núm. 1, Xàbia
UDI interdisciplinar IES Núm. 1, XàbiaUDI interdisciplinar IES Núm. 1, Xàbia
UDI interdisciplinar IES Núm. 1, XàbiaRaquel Gómez Paredes
 
When i think about the lord
When i think about the lordWhen i think about the lord
When i think about the lordandrew_mau77
 
Nota BMM
Nota BMM Nota BMM
Nota BMM arie-93
 
TODAY IS THE DAY
TODAY IS THE DAYTODAY IS THE DAY
TODAY IS THE DAYjeeane
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++Ilio Catallo
 
Modelo de UDI "Nos vamos de visita cultural" 1º ESO
Modelo de UDI  "Nos vamos de visita cultural" 1º ESOModelo de UDI  "Nos vamos de visita cultural" 1º ESO
Modelo de UDI "Nos vamos de visita cultural" 1º ESOalvaroge
 
Visit Saimaa - Yhteenveto UEF:n tutkimuksista
Visit Saimaa - Yhteenveto UEF:n tutkimuksistaVisit Saimaa - Yhteenveto UEF:n tutkimuksista
Visit Saimaa - Yhteenveto UEF:n tutkimuksistaMatkailufoorumi
 
MVC for Desktop Application - Part 1
MVC for Desktop Application - Part 1MVC for Desktop Application - Part 1
MVC for Desktop Application - Part 1晟 沈
 
Libro lenguaje 1° actividades
Libro lenguaje  1° actividadesLibro lenguaje  1° actividades
Libro lenguaje 1° actividadesXimena Vergara
 
Data structures and algorithms lab5
Data structures and algorithms lab5Data structures and algorithms lab5
Data structures and algorithms lab5Bianca Teşilă
 

Viewers also liked (20)

Desafío No. 31
Desafío No. 31Desafío No. 31
Desafío No. 31
 
Lecciones aprendidas en otros contextos
Lecciones aprendidas en otros contextosLecciones aprendidas en otros contextos
Lecciones aprendidas en otros contextos
 
Uni papua fc landak unit mempawah hulu doing excersice
Uni papua fc landak unit mempawah hulu doing excersiceUni papua fc landak unit mempawah hulu doing excersice
Uni papua fc landak unit mempawah hulu doing excersice
 
Qno 1 (d)
Qno 1 (d)Qno 1 (d)
Qno 1 (d)
 
7
77
7
 
Marketing Case Studies
Marketing Case StudiesMarketing Case Studies
Marketing Case Studies
 
UDI interdisciplinar IES Núm. 1, Xàbia
UDI interdisciplinar IES Núm. 1, XàbiaUDI interdisciplinar IES Núm. 1, Xàbia
UDI interdisciplinar IES Núm. 1, Xàbia
 
Network Marketing
Network MarketingNetwork Marketing
Network Marketing
 
When i think about the lord
When i think about the lordWhen i think about the lord
When i think about the lord
 
Nota BMM
Nota BMM Nota BMM
Nota BMM
 
TODAY IS THE DAY
TODAY IS THE DAYTODAY IS THE DAY
TODAY IS THE DAY
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++
 
Comic uni papua ke 7
Comic uni papua ke   7Comic uni papua ke   7
Comic uni papua ke 7
 
Modelo de UDI "Nos vamos de visita cultural" 1º ESO
Modelo de UDI  "Nos vamos de visita cultural" 1º ESOModelo de UDI  "Nos vamos de visita cultural" 1º ESO
Modelo de UDI "Nos vamos de visita cultural" 1º ESO
 
Un bautismo efesios 4.5
Un bautismo efesios 4.5Un bautismo efesios 4.5
Un bautismo efesios 4.5
 
Visit Saimaa - Yhteenveto UEF:n tutkimuksista
Visit Saimaa - Yhteenveto UEF:n tutkimuksistaVisit Saimaa - Yhteenveto UEF:n tutkimuksista
Visit Saimaa - Yhteenveto UEF:n tutkimuksista
 
MVC for Desktop Application - Part 1
MVC for Desktop Application - Part 1MVC for Desktop Application - Part 1
MVC for Desktop Application - Part 1
 
8 Pointers
8 Pointers8 Pointers
8 Pointers
 
Libro lenguaje 1° actividades
Libro lenguaje  1° actividadesLibro lenguaje  1° actividades
Libro lenguaje 1° actividades
 
Data structures and algorithms lab5
Data structures and algorithms lab5Data structures and algorithms lab5
Data structures and algorithms lab5
 

Similar to 4 Classes & Objects

Similar to 4 Classes & Objects (20)

Chapter18 class-and-objects
Chapter18 class-and-objectsChapter18 class-and-objects
Chapter18 class-and-objects
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Class and object
Class and objectClass and object
Class and object
 
Class-١.pptx vbdbbdndgngngndngnnfndfnngn
Class-١.pptx vbdbbdndgngngndngnnfndfnngnClass-١.pptx vbdbbdndgngngndngnnfndfnngn
Class-١.pptx vbdbbdndgngngndngnnfndfnngn
 
Class and object
Class and objectClass and object
Class and object
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
 
Learn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & InheritanceLearn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & Inheritance
 
chapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdfchapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdf
 
Class properties
Class propertiesClass properties
Class properties
 
C++ Notes
C++ NotesC++ Notes
C++ Notes
 
Class objects oopm
Class objects oopmClass objects oopm
Class objects oopm
 
Member Function in C++
Member Function in C++ Member Function in C++
Member Function in C++
 
Member Function in C++
Member Function in C++Member Function in C++
Member Function in C++
 
Lecture 2 (1)
Lecture 2 (1)Lecture 2 (1)
Lecture 2 (1)
 
+2 CS class and objects
+2 CS class and objects+2 CS class and objects
+2 CS class and objects
 
Classes-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdfClasses-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdf
 
Classes
ClassesClasses
Classes
 
Oops
OopsOops
Oops
 
My c++
My c++My c++
My c++
 

More from Praveen M Jigajinni

Chapter 09 design and analysis of algorithms
Chapter 09  design and analysis of algorithmsChapter 09  design and analysis of algorithms
Chapter 09 design and analysis of algorithmsPraveen M Jigajinni
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructorsPraveen M Jigajinni
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programmingPraveen M Jigajinni
 
Chapter 8 getting started with python
Chapter 8 getting started with pythonChapter 8 getting started with python
Chapter 8 getting started with pythonPraveen M Jigajinni
 
Chapter 7 basics of computational thinking
Chapter 7 basics of computational thinkingChapter 7 basics of computational thinking
Chapter 7 basics of computational thinkingPraveen M Jigajinni
 
Chapter 6 algorithms and flow charts
Chapter 6  algorithms and flow chartsChapter 6  algorithms and flow charts
Chapter 6 algorithms and flow chartsPraveen M Jigajinni
 

More from Praveen M Jigajinni (20)

Chapter 09 design and analysis of algorithms
Chapter 09  design and analysis of algorithmsChapter 09  design and analysis of algorithms
Chapter 09 design and analysis of algorithms
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructors
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programming
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
 
Unit 3 MongDB
Unit 3 MongDBUnit 3 MongDB
Unit 3 MongDB
 
Chapter 17 Tuples
Chapter 17 TuplesChapter 17 Tuples
Chapter 17 Tuples
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
 
Chapter 13 exceptional handling
Chapter 13 exceptional handlingChapter 13 exceptional handling
Chapter 13 exceptional handling
 
Chapter 10 data handling
Chapter 10 data handlingChapter 10 data handling
Chapter 10 data handling
 
Chapter 9 python fundamentals
Chapter 9 python fundamentalsChapter 9 python fundamentals
Chapter 9 python fundamentals
 
Chapter 8 getting started with python
Chapter 8 getting started with pythonChapter 8 getting started with python
Chapter 8 getting started with python
 
Chapter 7 basics of computational thinking
Chapter 7 basics of computational thinkingChapter 7 basics of computational thinking
Chapter 7 basics of computational thinking
 
Chapter 6 algorithms and flow charts
Chapter 6  algorithms and flow chartsChapter 6  algorithms and flow charts
Chapter 6 algorithms and flow charts
 
Chapter 5 boolean algebra
Chapter 5 boolean algebraChapter 5 boolean algebra
Chapter 5 boolean algebra
 
Chapter 4 number system
Chapter 4 number systemChapter 4 number system
Chapter 4 number system
 

Recently uploaded

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 

Recently uploaded (20)

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 

4 Classes & Objects

  • 1. WEL COME PRAVEEN M JIGAJINNI PGT (Computer Science) MTech[IT],MPhil (Comp.Sci), MCA, MSc[IT], PGDCA, ADCA, Dc. Sc. & Engg. email: praveenkumarjigajinni@yahoo.co.in
  • 3. What is Class? The mechanism that allows you to combine data and the function in a single unit is called a class. Once a class is defined, you can declare variables of that type. A class variable is called object or instance. In other words, a class would be the data type, and an object would be the variable. Classes are generally declared using the keyword class.
  • 4. What is Class? A class is the collection of related data and function under a single name. A C++ program can have any number of classes. When related data and functions are kept under a class, it helps to visualize the complex problem efficiently and effectively.
  • 5. What is Class? A class is a definition of an object. It's a type just like int . A class resembles a struct with just one difference : all struct members are public by default. All classes members are private. Objects are the biggest difference between C+ + and C . One of the earliest names for C++ was C with Classes. Remember : A class is a type, and an object of this class is just a variable.
  • 6. What is Class? A class is a user defined type or data structure declared with keyword class that has data and functions (also called methods) as its members whose access is governed by the three access specifiers private, protected or public (by default access to members of a class is private). A class (declared with keyword class) in C++ differs from a structure (declared with keyword struct) as by default, members are private in a class while they are public in a structure.
  • 7. What is Class? The private members are not accessible outside the class; they can be accessed only through methods of the class. The public members form an interface to the class and are accessible outside the class. Instances of these data types are known as objects and can contain member variables, constants, member functions, and overloaded operators defined by the programmer.
  • 8. Defining Class class class_name { Data Members; Methods; }; OR class class_name { private: members1; protected: members2; public: members3; };
  • 9. Defining Class Where class_name is a valid identifier for the class. The body of the declaration can contain members, that can be either data or function declarations, The members of a class are classified into three categories: private, public, and protected. private, protected, and public are reserved words and are called member access specifies. These specifies modify the access rights that the members following them acquire.
  • 10. Defining Class private members of a class are accessible only from within other members of the same class. You cannot access it outside of the class. protected members are accessible from members of their same class and also from members of their derived classes. protected members are accessible from other members of the same class (or from their "friends"), but also from members of their derived classes.
  • 11. Defining Class Finally, public members are accessible from anywhere where the object is visible. By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before one other class specifies automatically has private access.
  • 12. Defining Class Example class Circle { private: double radius; public: void setRadius(double r) { radius = r; } double getArea() { return 3.14 * radius * radius; } };
  • 13. Defining Member Function of Class Member functions can be defined in two ways, 1.Inside the class 2.Outside the class
  • 14. Defining Member Function of Class 1.Inside the class You can define Functions inside the class as shown in previous slides. Member functions defined inside a class this way are created as inline functions by default. It is also possible to declare a function within a class but define it elsewhere. Functions defined outside the class are not normally inline. When we define a function outside the class we cannot reference them (directly) outside of the class. In order to reference these, we use the scope resolution operator, :: (double colon). In this example, we are defining function setRadius outside the class:
  • 15. Defining Member Function of Class 2. Outside the class A large program may contain many member functions. For the clarity of the code, member functions can be defined outside the class. To do so, member function should be declared inside the class(function prototype should be inside the class). Then, the function definition can be defined using scope resolution operator ::.
  • 16. Defining Member Function of Class 2. Outside the class When we define a function outside the class we cannot reference them (directly) outside of the class. In order to reference these, we use the scope resolution operator, :: (double colon). In this example, we are defining function setRadius outside the class: void Circle :: setRadius(double r) { radius = r; }
  • 17. Object Declaration Once a class is defined, you can declare objects of that type. The syntax for declaring a object is the same as that for declaring any other variable. The following statements declare two objects of type circle: Circle c1, c2; Circle is class and c1 and c2 are the objects. Once the class is defined you can define any number of objects.
  • 18. Object Declaration Accessing Class Members Once an object of a class is declared, it can access the public members of the class using ( . ) dot membership operator. c1.setRadius(2.5);
  • 19. Arrays within Class The array can be used as member variables in a class. The following class definition is valid. const int size=10; class array { int a[size]; public: void setval(void); void display(void); };
  • 20. Arrays within Class The array variable a[] declared as private member of the class array can be used in the member function, like any other array variable. We can perform any operations on it. For instance, in the above class definition, the member function setval() sets the value of element of the array a[], and display() function displays the values. Similarly, we may use other member functions to perform any other operation on the array values.
  • 21. Access modifiers Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components
  • 22. Access modifiers In C++, there are only three access modifiers. C# extends the number of them to five, while Java has four access modifiers,[2] but three keywords for this purpose. In Java, having no keyword before defaults to the package-private modifier. Access specifiers for classes:- When a class is declared as public, it is accessible to other classes defined in the same package as well as those defined in other packages. This is the most commonly used specifier for classes.
  • 23. Access modifiers A class cannot be declared as private. If no access specifier is stated, the default access restrictions will be applied. The class will be accessible to other classes in the same package but will be inaccessible to classes outside the package. When we say that a class is inaccessible, it simply means that we cannot create an object of that class or declare a variable of that class type. The protected access specifier too cannot be applied to a class.
  • 24. Access modifiers C++ uses the three modifiers called public, protected, and private. C# has the modifiers public, protected , internal, private, and protected internal. Java has public, package, protected, and private.
  • 25. Local Classes in C++ A class declared inside a function becomes local to that function and is called Local Class in C++. For example, in the following program, Test is a local class in fun(). void fun() { class Test // local to fun { /* members of Test class */ }; }
  • 26. Global Classes in C++ A class declared outside the body of all the function in a program is called Global Class in C++. For example class sample { int x; public: void readx() { cin>>x;} }; void main() { sample s1; s1.readx(); }
  • 27. Local and Global Objects in C++ A class declared outside the body of all the function in a program is called Global Class in C++. For example class sample { int x; public: void readx() { cin>>x;} }; sample s1; // Global Object void main() { sample s2; // Local Object s1.readx(); }
  • 28. STATIC FUNCTION MEMBERS • We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. • A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. We can't put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to.
  • 29. STATIC FUNCTION MEMBERS • By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::. • A static member function can only access static data member, other static member functions and any other functions from outside the class. • Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not.
  • 30. class test { static int i; public: void static geti() { ++i; } void printi() { cout<<"n i val is = "<<i; } }; int test :: i=0; // needs to be initilized. void main() { clrscr(); test t1, t2; t1.geti(); t2.geti(); t1.printi(); getch(); }
  • 31. What is C++ inline functions In C, we have used Macro function an optimized technique used by compiler to reduce the execution time etc. So Question comes in mind that what’s there in C++ for that and in what all better ways? Inline function is introduced which is an optimization technique used by the compilers especially to reduce the execution time. We will cover “what, why, when & how” of inline functions.
  • 32. What is C++ inline functions The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime. Inline functions are defined with inline keyword. For Example: inline int sqr(int x) { int y; y = x * x; return y; }
  • 33. What is C++ inline functions Pros :- 1. It speeds up your program by avoiding function calling overhead. 2. It save overhead of variables push/pop on the stack, when function calling happens. 3. It save overhead of return call from a function. 4. It increases locality of reference by utilizing instruction cache.
  • 34. What is C++ inline functions Pros 5. By marking it as inline, you can put a function definition in a header file (i.e. it can be included in multiple compilation unit, without the linker complaining)
  • 35. What is C++ inline functions Cons :- 1. It increases the executable size due to code expansion. 2. C++ inlining is resolved at compile time. Which means if you change the code of the inlined function, you would need to recompile all the code using it to make sure it will be updated. 3. When used in a header, it makes your header file larger with information which users don’t care.
  • 36. What is C++ inline functions Cons :- 4. As mentioned above it increases the executable size, which may cause thrashing in memory. More number of page fault bringing down your program performance. 5. Sometimes not useful for example in embedded system where large executable size is not preferred at all due to memory constraints.
  • 37. When inline functions do not work? The function should be inlined only when they are small. There is no point in inlining large functions as there would be heavy memory penalty. The linlining does not work for the following situations. 1.For a functions that returns the values and are having a loop or a switch or goto statements. 2.For a functions not returning values, if return statement exists. 3.If a functions contain static variables. 4.If the function is recursive.
  • 38. FRIEND FUNCTION A friend function is a function that is not a member of a class but has access to the class's private and protected members. Friend functions are not considered class members; they are normal external functions that are given special access privileges. To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend as follows:
  • 39. FRIEND FUNCTION Friend functions have the following properties: 1)Friend of the class can be member of some other class. 2) Friend of one class can be friend of another class or all the classes in one program, such a friend is known as GLOBAL FRIEND. 3) Friend can access the private or protected members of the class in which they are declared to be friend, but they can use the members for a specific object.
  • 40. FRIEND FUNCTION Friend functions have the following properties: 4) Friends are non-members hence do not get “this” pointer. 5) Friends, can be friend of more than one class, hence they can be used for message passing between the classes. 6) Friend can be declared anywhere (in public, protected or private section) in the class.
  • 41. FRIEND FUNCTION – AN EXAMPLE class base { int val1,val2; public: void get() { cout<<"Enter two values:"; cin>>val1>>val2; } friend float mean(base ob); };
  • 42. FRIEND FUNCTION – AN EXAMPLE float mean(base ob) { return float(ob.val1+ob.val2)/2; } void main() { clrscr(); base obj; obj.get(); cout<<"n Mean value is : "<<mean(obj); getch(); }
  • 43. FRIEND CLASS A class can also be declared to be the friend of some other class. When we create a friend class then all the member functions of the friend class also become the friend of the other class. This requires the condition that the friend becoming class must be first declared or defined (forward declaration).
  • 44. FRIEND CLASS class MyClass { friend class SecondClass; // Declare a friend class public: MyClass() : Secret(0){} void printMember() { cout << Secret << endl; } private: int Secret; };
  • 45. FRIEND CLASS class SecondClass { public: void change( MyClass& yourclass, int x ) { yourclass.Secret = x; } };
  • 46. FRIEND CLASS void main() { MyClass my_class; SecondClass sec_class; my_class.printMember(); sec_class.change(my_class,5); my_class.printMember(); } Note: we declared friend class SecondClass; in the class MyClass, so we can access Secret in the class SecondClass. Contd…
  • 47. FRIEND CLASS Another property of friendships is that they are not transitive: The friend of a friend is not considered to be a friend unless explicitly specified.