SlideShare a Scribd company logo
1 of 75
Elements of OOPs
1. Class
2. Object
3. Encapsulation
4. Data Abstraction
5. Data Hiding
6. Message Passing
7. Inheritance
8. Polymorphism
Slide No.
15 September 2022 1
Class
• Class is a user-defined data type.
• A class is like a blueprint for an object.
• It is a logical entity.
• Class represents objects of similar type.
Slide No.
15 September 2022 2
Objects
• An object can be defined as an instance of class
• There can be multiple instance of a class in a program.
• An object is a real world entity.
• An object has state and behavior.
Slide No.
15 September 2022 3
• Encapsulation is defined as binding together the data and the
functions that manipulate them.
Encapsulation
Slide No.
15 September 2022 4
State/Attributes/Properties/
Variables
Behaviour/Functions/
Methods
Identity of Object
• Identity is the property of a object which distinguishes it
from all other objects.
• Humans have id numbers, fingerprints, DNA profiles. All
these are representations of the fact that we are each
unique and identifiable.
• This element of the object model can be confused
with state. State is the set of values that an object
encapsulates. Two objects may have identical state, and
yet are still separate, distinct, identifiable objects.
• Objects in an OO system have distinct identity.
Example of an object “dog”
Defining class in C++
class class_name
{
access modifiers //private, protected, public
data members // defines the state/attributes
constructors // initialise the object
functions members // define behaviour
destructor //do clean-up like free memory, close
// files, close connections etc.
}; //end of class
class SavingAccount
{
string name;
int id;
float balance;
Void debit_account(float amount);
Void credit_account( float amount);
Void show();
}
Defining a class for saving bank account object
data members-defining
state/attributes of
saving account
function/method
members -defining
behaviour of saving
account
Adding body of function members
class SavingAccount
{
string name;
int id;
float balance;
Void debit_account(float amount)
{
balance = balance – amount;
}
Void credit_account( float amount);
}
Void SavingAccount::credit_account( float amount)
{
balance = balance + amount;
}
Scope resolution
operator (::)
Instance
• An Object is an instance of a Class. When a class is
defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is
allocated.
By declaring a variable of
object
int main()
{
SavingAccount sa;
sa. name = “Akhil”;
sa.id = 101;
sa.balance = 500;
sa.credit_account(100);
}
Creating object (instance) of saving account and
accessing members in C++
By using new keyword and
pointer variable
int main()
{
SavingAccount *sb
= new SavingAccount();
sb-> name = “Akhil”;
sb->id = 101;
sb->balance = 500;
sb->credit_account(100);
}
By declaring a variable of
object
int main()
{
SavingAccount sa,sb,sc;
}
Instances of class and Identity of objects in c++
SavinAccount
Class
sa sb sc
instances(objects)
of class
SavingAccount
Each variable name serves as an Identity of
the object in given scope. Each variable has
an memory associated with it which
uniquely distinguishes it from other objects
Abstraction
Consider a real-life example: A man driving a car. The man only
knows that pressing the accelerators will increase the speed of
the car or applying brakes will stop the car but he does not
know about its internal mechanism.
Abstraction
Abstraction is used to display only the
important set of services or functionalities to
the users and hide the internal implementation
details of the object.
Slide No.
15 September 2022 15
Data Hiding
• is the process that hides the internal data and restricts it from
directly getting accessed by the program for unauthorized
access.
• It is achieved by using access specifiers - private and
protected modifiers.
Slide No.
15 September 2022 16
Access specifiers:
Access specifiers:
Access specifiers:
Data hinding using access modifiers
class SavingAccount
{
private:
Int amount;
int ac_ID;
string name;
public:
Void debit_account(int debit_amount);
Void credit_account( int credit_amount);
void show();
}
using access modifiers to secure the object
class SavingAccount
{
private:
Int amount;
int ac_ID;
string name;
public:
Void debit_account(int debit_amount);
Void credit_account( int credit_amount);
void show();
}
Int main()
{
SavingAccount sa;
sa. name = “Akhil”;
sa.id = 101;
sa.balance = 500;
sa.credit_account(100);
}
Now we can not initialize
members from outside
So how to initialise data members - Use constructors
Constructor in C++
• The name of the constructor is the same as its class
name.
• Constructors do not return values; hence they do not
have a return type.
• A constructor gets called automatically when we
create the object of the class.
• Constructors are mostly declared in the public section
of the class though it can be declared in the private
section of the class.
• Constructors can be overloaded.
• Constructor can not be declared virtual.
Int main()
{
SavingAccount sa(“amit”,
101, 500);
}
Using constructors to initialise the object
class SavingAccount
{
private:
string name;
int id;
float balance;
public:
SavingAccount( string name, int id, float amount)
{
SavingAccount::name = name;
SavingAccount::id = id;
balance = amount;
}
Void debit_account(float amount);
Void credit_account( float amount);
void show();
}
Types of cunstructor
• Default Constructor
• Parameterized Constructor
• Copy Constructor
Default Constructor
• The default constructor is the constructor which
doesn’t take any argument or takes only default
arguments.
• A default constructor is so important for the
initialization of object members, that even if we
do not define a constructor explicitly, the compiler
will provide a default constructor implicitly
Default Constructor
class Point
{
private:
int x, y;
public:
Point()
{
x=10;
y=10;
}
void show(){
cout << “pos-x = “ << x;
cout << “Pos-y = “ << y;
}
int main()
{
Point p;
p.print();
}
Output:
pos-x = 10
pos-y = 10
Default Constructor
class Point
{
private:
int x, y;
public:
Point(int xp=10, int yp=10)
{
x=xp;
y=yp;
}
void show(){
cout << “pos-x = “ << x;
cout << “Pos-y = “ << y;
}
int main()
{
Point p;
p.print();
}
Output:
pos-x = 10
pos-y = 10
Default Constructor
class Point
{
private:
int x, y;
public:
Point(int xp, int yp)
{
x=xp;
y=yp;
}
void show(){
cout << “pos-x = “ << x;
cout << “Pos-y = “ << y;
}
int main()
{
Point p;
p.print();
}
Output:
Error – no default constructor
note: if we define a constructor
then compiler won’t provide
default construtor we must
define a deafult constructor as
well
Parameterized Constructor
• The pameterized
constructor is always
takes arguments
including default
arguments.
class Point
{
private:
int x, y;
public:
Point(int xp, int yp)
{
x=xp;
y=yp;
}
}
Copy Constructor
• A copy constructor is a member function that
initializes an object using another object of the same
class.
• A copy constructor has the following general function
prototype:
• The copy constructor can be defined explicitly by the
programmer. If the programmer does not define the
copy constructor, the compiler does it for us.
ClassName (const ClassName &old_obj);
Copy Constructor Example
class Point
{
private:
int x, y;
public:
Point(int xp, int yp){
x=xp;
y=yp;
}
//copy constructor
Point( Point &p){
x = p.x;
y = p.y;
}
void show(){
cout << “pos-x = “ << x;
cout << “Pos-y = “ << y;
}
int main()
{
Point p(20,20);
Point p1(p), p2=p;
p1.print();
p2.print();
}
Output:
pos-x = 20
pos-y = 20
pos-x = 20
pos-y = 20
When Copy Constructor called
class Point
{
private:
int x, y;
public:
Point(int xp, int yp){
x=xp;
y=yp;
}
//copy constructor
Point( Point &p){
x = p.x;
y = p.y;
}
void show(){
cout << “pos-x = “ << x;
cout << “Pos-y = “ << y;
}
int main()
{
Point p(20,20);
Point p1(p);
Point p2=p;
Point p3(10,10);
p3 = p;
} assignment
operator
will be
called
copy
costructor
willl be
called
Default Copy Constructor
• If we don’t define our own copy constructor, the
C++ compiler creates a default copy constructor
for each class which does a member-wise copy
between objects.
• The compiler-created copy constructor works fine
in general. We need to define our own copy
constructor only if an object has pointers or any
runtime allocation of the resource like file handle,
a network connection, etc.
Copy Constructor and pointers
class Point
{
private:
int *x, *y;
public:
Point(int xp, int yp){
x= new int; *x = xp;
y= new int; *y =yp;
}
void setxy(int xp, int yp){
*x = xp; *y=yp;
}
void show(){
cout << “pos-x = “ << x;
cout << “Pos-y = “ << y;
}
int main()
{
Point p(20,20);
Point p1=p;
p.setxy(40,40)
p1.print();
}
Output:
pos-x = 40
pos-y = 40
result incorrect due to sallow copy
by default copy constructor, we
need to define copy constructor
with deep copy by allocating
memory for integers
Destructor in C++
Destructor is an instance member function which is
invoked automatically whenever an object is going
to be destroyed. Meaning, a destructor is the last
function that is going to be called before an object is
destroyed.
Destructor in C++
 Destructor is also a special member function like
constructor. Destructor destroys the class objects created by
constructor.
 Destructor has the same name as their class name preceded
by a tiled (~) symbol.
 It is not possible to define more than one destructor.
 The destructor is only one way to destroy the object create
by constructor. Hence destructor can-not be overloaded.
 Destructor neither requires any argument nor returns any
value.
 It is automatically called when object goes out of scope.
 Destructor release memory space occupied by the objects
created by constructor.
Destructor in C++
Syntax for defining the destructor within the class
~ <class-name>()
{
}
Syntax for defining the destructor outside the class
<class-name>: : ~ <class-name>()
{
}
Example:Destructor in C++
class Student {
private:
char* name;
int age;
int sem;
public:
Student(char* s) // constructor
{
size = strlen(s);
name = new char[size + 1];
strcpy(name, s);
}
~Student() // destructor
{
delete[] name;
}
};
Int main()
{
SavingAccount sa(“amit”, 101, 500);
cout << “account name: “ <<
sa.get_name();
cout << “account balance” <<
sa.get_bal();
}
Using getter and setter methods
Lets say we need report of all account
having name and balance but both these
members are private so solution is .. use
getter setter methods
class SavingAccount
{
private:
string name;
int id;
float balance;
public:
SavingAccount( string name, int id, float
amount)
{
SavingAccount::name = name;
SavingAccount::id = id;
balance = amount;
}
Void debit_account(float amount);
Void credit_account( float amount);
string get_name(){ return name; }
float get_bal(){ return balance; }
}
Message Passing
• Objects communicate with one another by
sending and receiving information to each other. A
message for an object is a request for execution of
a procedure and therefore will invoke a function in
the receiving object that generates the desired
results.
• Message passing involves specifying the name of
the object, the name of the function and the
information to be sent.
Message passing: Example
Bank object maintatns the accounts
by using message passing
int debit_account(float amount){
if(balance <= 0 )
return -1;
balance = balance – amount;
return 0;
}
Void credit_account( float amount){
balance = balance + amount;
}
string get_name(){ return name; }
float get_bal(){ return balance; }
}
class SavingAccount
{
private:
string name;
int id;
float balance;
public:
SavingAccount( string name, int id, float
amount)
{
SavingAccount::name = name;
SavingAccount::id = id;
balance = amount;
}
class Bank
{
private:
SavingAccount *sa[100];
int total_ac;
public:
Bank(){
total_ac =0;
}
void create_account(string name, int
amount)
{
sa[total_ac] = new
SavingAccount(name, total_ac,
amount);
total_ac++;
}
int deposit_amount( int ac_id, int
amount)
{
int res;
if (ac_id >= total_ac )
retrun -1;
res = sa[ac_id]-
>credit_account(amount);
return res;
}
int withdraw_amount(int ac_id, int
amount)
{
res = sa[ac_id]
->debit_account(amount);
return res;
}
}
int main
{
Bank my_bank();
int op_id = 0;
string name;
int ac_id =0, amount;
cout<< “Press 1. Create Account, 2. Withdraw, 3. Deposit, 4. Exit”
while(1)
{
cin >> op_id;
switch(op_id){
case 1:
cout<<“type name :”
cin >> name;
my_bank.create_account(name, 0);
break;
case 2:
cout<<“type account ID :”
cin >> ac_id;
cout<<“type amount to withdraw :”
cin >> amount;
my_bank. withdraw_amount(ac_id, amount);
break;
case 3:
cout<<“type account ID :”
cin >> ac_id;
cout<<“type amount to deposit :”
cin >> amount;
my_bank. deposit_amount(ac_id, amount);
break;
}
}
Static members of a Class
• They are shared by all instances of the class
• They do not belong to any particular instance of a
class
Static data members
• A variable that is part of a class, yet is not part of
an object of that class, is called static data
member
• Keyword static is used to make a data member
static
class ClassName{
…
static DataType VariableName;
};
Static data members
Defining Static Data Member
• Static data member is declared inside the class
• But they are defined outside the class
class ClassName{
…
static DataType VariableName;
};
DataType ClassName::VariableName;
Initializing Static Data Member
• Static data members should be initialized once at
file scope
• They are initialized at the time of definition
class Student{
private:
static int noOfStudents;
public:
…
};
int Student::noOfStudents = 0;
/*private static member cannot be accessed outside the
class except for initialization*/
Initializing Static Data Member
• If static data members are not explicitly initialized at
the time of definition then they are initialized to 0
int Student::noOfStudents;
is equivalent to
int Student::noOfStudents=0;
Accessing Static Data Member
• To access a static data member there are two ways
– Access like a normal data member
– Access using a scope resolution operator ‘::’
class Student{
public:
static int noOfStudents;
};
int Student::noOfStudents;
int main(){
Student aStudent;
aStudent.noOfStudents = 1;
Student::noOfStudents = 1;
}
Life of Static Data Member
• They are created even when there is no object of a class
• They remain in memory even when all objects of a class are
destroyed
class Student{
public:
static int noOfStudents;
};
int Student::noOfStudents;
int main(){
{
Student aStudent;
aStudent.noOfStudents = 1;
}
Student::noOfStudents = 1;
}
Uses
• They can be used to store information that is
required by all objects, like global variables
Example
Modify the class Student such that one can know
the number of student created in a system
Example
class Student{
…
public:
static int noOfStudents;
Student();
~Student();
…
};
int Student::noOfStudents = 0;
Student::Student(){
noOfStudents++;
}
Student::~Student(){
noOfStudents--;
}
Example
int Student::noOfStudents = 0;
int main(){
cout <<Student::noOfStudents <<endl;
Student studentA;
cout <<Student::noOfStudents <<endl;
Student studentB;
cout <<Student::noOfStudents <<endl;
}
Output:
0
1
2
Problem
• noOfStudents is accessible outside the class
• Bad design as the local data member is kept public
Static Member Function
Definition:
“The function that needs access to the
members of a class, yet does not need to be
invoked by a particular object, is called static
member function”
Static Member Function
• They are used to access static data members
• Access mechanism for static member functions is
same as that of static data members
• They cannot access any non-static members
Example
class Student{
static int noOfStudents;
int rollNo;
public:
static int getTotalStudent(){
return noOfStudents;
}
};
int Student::noOfStudents = 0;
int main(){
int i;
i = Student::getTotalStudents();
}
Example
class Student{
static int noOfStudents;
int rollNo;
public:
static int getTotalStudent(){
return rollNo;
}
};
int Student::getTotalStudents()= 0;
int main(){
int i;
i = Student::getTotalStudents();
/*Error: There is no instance of Student, rollNo cannot be
accessed*/
}
Instance and Static methods
63
C++ Data Types
structured
array struct union class
address
pointer reference
simple
integral enum
char short int long bool
floating
float double long double
64
Recall that . . .
char str [ 8 ];
• str is the base address of the array.
• We say str is a pointer because its value is an address.
• It is a pointer constant because the value of str itself
cannot be changed by assignment. It “points” to the
memory location of a char.
str [0] [1] [2] [3] [4] [5] [6] [7]
‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘0’
6000
65
Addresses in Memory
• When a variable is declared, enough memory to hold a
value of that type is allocated for it at an unused memory
location. This is the address of the variable
int x;
float number;
char ch;
2000 2002 2006
x number ch
66
Obtaining Memory Addresses
• The address of a non-array variable can be obtained by using
the address-of operator &
int x;
float number;
char ch;
cout << “Address of x is “ << &x << endl;
cout << “Address of number is “ << &number << endl;
cout << “Address of ch is “ << &ch << endl;
x number ch
2000 2002 2006
67
What is a pointer variable?
• A pointer variable is a variable whose value is the address of a
location in memory.
• To declare a pointer variable, you must specify the type of
value that the pointer will point to, for example,
int* ptr; // ptr will hold the address of an int
char* q; // q will hold the address of a char
68
Using a Pointer Variable
int x;
x = 12;
int* ptr;
ptr = &x;
NOTE: Because ptr holds the address of x,
we say that ptr “points to” x
2000
12
x
3000
2000
ptr
69
int x;
x = 12;
int* ptr;
ptr = &x;
cout << *ptr;
NOTE: The value pointed to by ptr is denoted by *ptr
*: dereference operator
2000
12
x
3000
2000
ptr
70
int x;
x = 12;
int* ptr;
ptr = &x;
*ptr = 5;
Using the Dereference Operator
2000
12
x
3000
2000
ptr
5
// changes the value at the
address ptr points to 5
71
char ch;
ch = ‘A’;
char* q;
q = &ch;
*q = ‘Z’;
char* p;
p = q;
Self –Test on Pointers
4000
A
ch
5000
4000
q
Z
6000
p
4000
// the rhs has value 4000
// now p and q both point to ch
72
ptr
Using a Pointer to Access the Elements of a
String
‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘0’
char msg[ ] =“Hello”;
char* ptr;
ptr = msg;
*ptr = ‘M’ ;
ptr++;
*ptr = ‘a’;
msg
3000
3000
‘M’ ‘a’
3001
73
Reference Variables
Reference variable = alias for another variable
- Contains the address of a variable (like a pointer)
- No need to perform any dereferencing (unlike a pointer)
- Must be initialized when it is declared
int x = 5;
int &z = x; // z is another name for x
int &y ; //Error: reference must be initialized
cout << x << endl; -> prints 5
cout << z << endl; -> prints 5
z = 9; // same as x = 9;
cout << x << endl; -> prints 9
cout << z << endl; -> prints 9
74
Why Reference Variables
• Are primarily used as function parameters
• Advantages of using references:
– you don’t have to pass the address of a variable
– you don’t have to dereference the variable inside the
called function
75
Reference Variables Example
#include <iostream.h>
// Function prototypes
(required in C++)
void p_swap(int *, int *);
void r_swap(int&, int&);
int main (void){
int v = 5, x = 10;
cout << v << x << endl;
p_swap(&v,&x);
cout << v << x << endl;
r_swap(v,x);
cout << v << x << endl;
return 0;
}
void r_swap(int &a, int &b)
{
int temp;
temp = a; (2)
a = b; (3)
b = temp;
}
void p_swap(int *a, int *b)
{
int temp;
temp = *a; (2)
*a = *b; (3)
*b = temp;
}

More Related Content

Similar to Class and object C++.pptx

Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Abu Saleh
 
While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...bhargavi804095
 
Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)SURBHI SAROHA
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptxRassjb
 
Constructor and Destructor.pdf
Constructor and Destructor.pdfConstructor and Destructor.pdf
Constructor and Destructor.pdfMadnessKnight
 
00-intro-to-classes.pdf
00-intro-to-classes.pdf00-intro-to-classes.pdf
00-intro-to-classes.pdfTamiratDejene1
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1Teksify
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOSPetr Dvorak
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)sdrhr
 
chapter-9-constructors.pdf
chapter-9-constructors.pdfchapter-9-constructors.pdf
chapter-9-constructors.pdfstudy material
 
7. Pointers and Virtual functions final -3.pptx
7. Pointers and Virtual functions final -3.pptx7. Pointers and Virtual functions final -3.pptx
7. Pointers and Virtual functions final -3.pptxAbhishekkumarsingh630054
 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2Aadil Ansari
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxSirRafiLectures
 

Similar to Class and object C++.pptx (20)

Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)
 
Introduction to java and oop
Introduction to java and oopIntroduction to java and oop
Introduction to java and oop
 
While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...
 
11-Classes.ppt
11-Classes.ppt11-Classes.ppt
11-Classes.ppt
 
Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
 
Day 1
Day 1Day 1
Day 1
 
Op ps
Op psOp ps
Op ps
 
Constructor and Destructor.pdf
Constructor and Destructor.pdfConstructor and Destructor.pdf
Constructor and Destructor.pdf
 
00-intro-to-classes.pdf
00-intro-to-classes.pdf00-intro-to-classes.pdf
00-intro-to-classes.pdf
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)
 
chapter-9-constructors.pdf
chapter-9-constructors.pdfchapter-9-constructors.pdf
chapter-9-constructors.pdf
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
7. Pointers and Virtual functions final -3.pptx
7. Pointers and Virtual functions final -3.pptx7. Pointers and Virtual functions final -3.pptx
7. Pointers and Virtual functions final -3.pptx
 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptx
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 

Recently uploaded

main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 

Recently uploaded (20)

main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 

Class and object C++.pptx

  • 1. Elements of OOPs 1. Class 2. Object 3. Encapsulation 4. Data Abstraction 5. Data Hiding 6. Message Passing 7. Inheritance 8. Polymorphism Slide No. 15 September 2022 1
  • 2. Class • Class is a user-defined data type. • A class is like a blueprint for an object. • It is a logical entity. • Class represents objects of similar type. Slide No. 15 September 2022 2
  • 3. Objects • An object can be defined as an instance of class • There can be multiple instance of a class in a program. • An object is a real world entity. • An object has state and behavior. Slide No. 15 September 2022 3
  • 4. • Encapsulation is defined as binding together the data and the functions that manipulate them. Encapsulation Slide No. 15 September 2022 4 State/Attributes/Properties/ Variables Behaviour/Functions/ Methods
  • 5. Identity of Object • Identity is the property of a object which distinguishes it from all other objects. • Humans have id numbers, fingerprints, DNA profiles. All these are representations of the fact that we are each unique and identifiable. • This element of the object model can be confused with state. State is the set of values that an object encapsulates. Two objects may have identical state, and yet are still separate, distinct, identifiable objects. • Objects in an OO system have distinct identity.
  • 6.
  • 7. Example of an object “dog”
  • 8. Defining class in C++ class class_name { access modifiers //private, protected, public data members // defines the state/attributes constructors // initialise the object functions members // define behaviour destructor //do clean-up like free memory, close // files, close connections etc. }; //end of class
  • 9. class SavingAccount { string name; int id; float balance; Void debit_account(float amount); Void credit_account( float amount); Void show(); } Defining a class for saving bank account object data members-defining state/attributes of saving account function/method members -defining behaviour of saving account
  • 10. Adding body of function members class SavingAccount { string name; int id; float balance; Void debit_account(float amount) { balance = balance – amount; } Void credit_account( float amount); } Void SavingAccount::credit_account( float amount) { balance = balance + amount; } Scope resolution operator (::)
  • 11. Instance • An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.
  • 12. By declaring a variable of object int main() { SavingAccount sa; sa. name = “Akhil”; sa.id = 101; sa.balance = 500; sa.credit_account(100); } Creating object (instance) of saving account and accessing members in C++ By using new keyword and pointer variable int main() { SavingAccount *sb = new SavingAccount(); sb-> name = “Akhil”; sb->id = 101; sb->balance = 500; sb->credit_account(100); }
  • 13. By declaring a variable of object int main() { SavingAccount sa,sb,sc; } Instances of class and Identity of objects in c++ SavinAccount Class sa sb sc instances(objects) of class SavingAccount Each variable name serves as an Identity of the object in given scope. Each variable has an memory associated with it which uniquely distinguishes it from other objects
  • 14. Abstraction Consider a real-life example: A man driving a car. The man only knows that pressing the accelerators will increase the speed of the car or applying brakes will stop the car but he does not know about its internal mechanism.
  • 15. Abstraction Abstraction is used to display only the important set of services or functionalities to the users and hide the internal implementation details of the object. Slide No. 15 September 2022 15
  • 16. Data Hiding • is the process that hides the internal data and restricts it from directly getting accessed by the program for unauthorized access. • It is achieved by using access specifiers - private and protected modifiers. Slide No. 15 September 2022 16
  • 17.
  • 21. Data hinding using access modifiers class SavingAccount { private: Int amount; int ac_ID; string name; public: Void debit_account(int debit_amount); Void credit_account( int credit_amount); void show(); }
  • 22. using access modifiers to secure the object class SavingAccount { private: Int amount; int ac_ID; string name; public: Void debit_account(int debit_amount); Void credit_account( int credit_amount); void show(); } Int main() { SavingAccount sa; sa. name = “Akhil”; sa.id = 101; sa.balance = 500; sa.credit_account(100); } Now we can not initialize members from outside So how to initialise data members - Use constructors
  • 23. Constructor in C++ • The name of the constructor is the same as its class name. • Constructors do not return values; hence they do not have a return type. • A constructor gets called automatically when we create the object of the class. • Constructors are mostly declared in the public section of the class though it can be declared in the private section of the class. • Constructors can be overloaded. • Constructor can not be declared virtual.
  • 24. Int main() { SavingAccount sa(“amit”, 101, 500); } Using constructors to initialise the object class SavingAccount { private: string name; int id; float balance; public: SavingAccount( string name, int id, float amount) { SavingAccount::name = name; SavingAccount::id = id; balance = amount; } Void debit_account(float amount); Void credit_account( float amount); void show(); }
  • 25. Types of cunstructor • Default Constructor • Parameterized Constructor • Copy Constructor
  • 26. Default Constructor • The default constructor is the constructor which doesn’t take any argument or takes only default arguments. • A default constructor is so important for the initialization of object members, that even if we do not define a constructor explicitly, the compiler will provide a default constructor implicitly
  • 27. Default Constructor class Point { private: int x, y; public: Point() { x=10; y=10; } void show(){ cout << “pos-x = “ << x; cout << “Pos-y = “ << y; } int main() { Point p; p.print(); } Output: pos-x = 10 pos-y = 10
  • 28. Default Constructor class Point { private: int x, y; public: Point(int xp=10, int yp=10) { x=xp; y=yp; } void show(){ cout << “pos-x = “ << x; cout << “Pos-y = “ << y; } int main() { Point p; p.print(); } Output: pos-x = 10 pos-y = 10
  • 29. Default Constructor class Point { private: int x, y; public: Point(int xp, int yp) { x=xp; y=yp; } void show(){ cout << “pos-x = “ << x; cout << “Pos-y = “ << y; } int main() { Point p; p.print(); } Output: Error – no default constructor note: if we define a constructor then compiler won’t provide default construtor we must define a deafult constructor as well
  • 30. Parameterized Constructor • The pameterized constructor is always takes arguments including default arguments. class Point { private: int x, y; public: Point(int xp, int yp) { x=xp; y=yp; } }
  • 31. Copy Constructor • A copy constructor is a member function that initializes an object using another object of the same class. • A copy constructor has the following general function prototype: • The copy constructor can be defined explicitly by the programmer. If the programmer does not define the copy constructor, the compiler does it for us. ClassName (const ClassName &old_obj);
  • 32. Copy Constructor Example class Point { private: int x, y; public: Point(int xp, int yp){ x=xp; y=yp; } //copy constructor Point( Point &p){ x = p.x; y = p.y; } void show(){ cout << “pos-x = “ << x; cout << “Pos-y = “ << y; } int main() { Point p(20,20); Point p1(p), p2=p; p1.print(); p2.print(); } Output: pos-x = 20 pos-y = 20 pos-x = 20 pos-y = 20
  • 33. When Copy Constructor called class Point { private: int x, y; public: Point(int xp, int yp){ x=xp; y=yp; } //copy constructor Point( Point &p){ x = p.x; y = p.y; } void show(){ cout << “pos-x = “ << x; cout << “Pos-y = “ << y; } int main() { Point p(20,20); Point p1(p); Point p2=p; Point p3(10,10); p3 = p; } assignment operator will be called copy costructor willl be called
  • 34. Default Copy Constructor • If we don’t define our own copy constructor, the C++ compiler creates a default copy constructor for each class which does a member-wise copy between objects. • The compiler-created copy constructor works fine in general. We need to define our own copy constructor only if an object has pointers or any runtime allocation of the resource like file handle, a network connection, etc.
  • 35. Copy Constructor and pointers class Point { private: int *x, *y; public: Point(int xp, int yp){ x= new int; *x = xp; y= new int; *y =yp; } void setxy(int xp, int yp){ *x = xp; *y=yp; } void show(){ cout << “pos-x = “ << x; cout << “Pos-y = “ << y; } int main() { Point p(20,20); Point p1=p; p.setxy(40,40) p1.print(); } Output: pos-x = 40 pos-y = 40 result incorrect due to sallow copy by default copy constructor, we need to define copy constructor with deep copy by allocating memory for integers
  • 36. Destructor in C++ Destructor is an instance member function which is invoked automatically whenever an object is going to be destroyed. Meaning, a destructor is the last function that is going to be called before an object is destroyed.
  • 37. Destructor in C++  Destructor is also a special member function like constructor. Destructor destroys the class objects created by constructor.  Destructor has the same name as their class name preceded by a tiled (~) symbol.  It is not possible to define more than one destructor.  The destructor is only one way to destroy the object create by constructor. Hence destructor can-not be overloaded.  Destructor neither requires any argument nor returns any value.  It is automatically called when object goes out of scope.  Destructor release memory space occupied by the objects created by constructor.
  • 38. Destructor in C++ Syntax for defining the destructor within the class ~ <class-name>() { } Syntax for defining the destructor outside the class <class-name>: : ~ <class-name>() { }
  • 39. Example:Destructor in C++ class Student { private: char* name; int age; int sem; public: Student(char* s) // constructor { size = strlen(s); name = new char[size + 1]; strcpy(name, s); } ~Student() // destructor { delete[] name; } };
  • 40. Int main() { SavingAccount sa(“amit”, 101, 500); cout << “account name: “ << sa.get_name(); cout << “account balance” << sa.get_bal(); } Using getter and setter methods Lets say we need report of all account having name and balance but both these members are private so solution is .. use getter setter methods class SavingAccount { private: string name; int id; float balance; public: SavingAccount( string name, int id, float amount) { SavingAccount::name = name; SavingAccount::id = id; balance = amount; } Void debit_account(float amount); Void credit_account( float amount); string get_name(){ return name; } float get_bal(){ return balance; } }
  • 41. Message Passing • Objects communicate with one another by sending and receiving information to each other. A message for an object is a request for execution of a procedure and therefore will invoke a function in the receiving object that generates the desired results. • Message passing involves specifying the name of the object, the name of the function and the information to be sent.
  • 42. Message passing: Example Bank object maintatns the accounts by using message passing int debit_account(float amount){ if(balance <= 0 ) return -1; balance = balance – amount; return 0; } Void credit_account( float amount){ balance = balance + amount; } string get_name(){ return name; } float get_bal(){ return balance; } } class SavingAccount { private: string name; int id; float balance; public: SavingAccount( string name, int id, float amount) { SavingAccount::name = name; SavingAccount::id = id; balance = amount; }
  • 43. class Bank { private: SavingAccount *sa[100]; int total_ac; public: Bank(){ total_ac =0; } void create_account(string name, int amount) { sa[total_ac] = new SavingAccount(name, total_ac, amount); total_ac++; } int deposit_amount( int ac_id, int amount) { int res; if (ac_id >= total_ac ) retrun -1; res = sa[ac_id]- >credit_account(amount); return res; } int withdraw_amount(int ac_id, int amount) { res = sa[ac_id] ->debit_account(amount); return res; } }
  • 44. int main { Bank my_bank(); int op_id = 0; string name; int ac_id =0, amount; cout<< “Press 1. Create Account, 2. Withdraw, 3. Deposit, 4. Exit” while(1) { cin >> op_id; switch(op_id){ case 1: cout<<“type name :” cin >> name; my_bank.create_account(name, 0); break;
  • 45. case 2: cout<<“type account ID :” cin >> ac_id; cout<<“type amount to withdraw :” cin >> amount; my_bank. withdraw_amount(ac_id, amount); break; case 3: cout<<“type account ID :” cin >> ac_id; cout<<“type amount to deposit :” cin >> amount; my_bank. deposit_amount(ac_id, amount); break; } }
  • 46. Static members of a Class • They are shared by all instances of the class • They do not belong to any particular instance of a class
  • 47. Static data members • A variable that is part of a class, yet is not part of an object of that class, is called static data member • Keyword static is used to make a data member static class ClassName{ … static DataType VariableName; };
  • 49. Defining Static Data Member • Static data member is declared inside the class • But they are defined outside the class class ClassName{ … static DataType VariableName; }; DataType ClassName::VariableName;
  • 50. Initializing Static Data Member • Static data members should be initialized once at file scope • They are initialized at the time of definition class Student{ private: static int noOfStudents; public: … }; int Student::noOfStudents = 0; /*private static member cannot be accessed outside the class except for initialization*/
  • 51. Initializing Static Data Member • If static data members are not explicitly initialized at the time of definition then they are initialized to 0 int Student::noOfStudents; is equivalent to int Student::noOfStudents=0;
  • 52. Accessing Static Data Member • To access a static data member there are two ways – Access like a normal data member – Access using a scope resolution operator ‘::’ class Student{ public: static int noOfStudents; }; int Student::noOfStudents; int main(){ Student aStudent; aStudent.noOfStudents = 1; Student::noOfStudents = 1; }
  • 53. Life of Static Data Member • They are created even when there is no object of a class • They remain in memory even when all objects of a class are destroyed class Student{ public: static int noOfStudents; }; int Student::noOfStudents; int main(){ { Student aStudent; aStudent.noOfStudents = 1; } Student::noOfStudents = 1; }
  • 54. Uses • They can be used to store information that is required by all objects, like global variables Example Modify the class Student such that one can know the number of student created in a system
  • 55. Example class Student{ … public: static int noOfStudents; Student(); ~Student(); … }; int Student::noOfStudents = 0; Student::Student(){ noOfStudents++; } Student::~Student(){ noOfStudents--; }
  • 56. Example int Student::noOfStudents = 0; int main(){ cout <<Student::noOfStudents <<endl; Student studentA; cout <<Student::noOfStudents <<endl; Student studentB; cout <<Student::noOfStudents <<endl; } Output: 0 1 2
  • 57. Problem • noOfStudents is accessible outside the class • Bad design as the local data member is kept public
  • 58. Static Member Function Definition: “The function that needs access to the members of a class, yet does not need to be invoked by a particular object, is called static member function”
  • 59. Static Member Function • They are used to access static data members • Access mechanism for static member functions is same as that of static data members • They cannot access any non-static members
  • 60. Example class Student{ static int noOfStudents; int rollNo; public: static int getTotalStudent(){ return noOfStudents; } }; int Student::noOfStudents = 0; int main(){ int i; i = Student::getTotalStudents(); }
  • 61. Example class Student{ static int noOfStudents; int rollNo; public: static int getTotalStudent(){ return rollNo; } }; int Student::getTotalStudents()= 0; int main(){ int i; i = Student::getTotalStudents(); /*Error: There is no instance of Student, rollNo cannot be accessed*/ }
  • 63. 63 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double
  • 64. 64 Recall that . . . char str [ 8 ]; • str is the base address of the array. • We say str is a pointer because its value is an address. • It is a pointer constant because the value of str itself cannot be changed by assignment. It “points” to the memory location of a char. str [0] [1] [2] [3] [4] [5] [6] [7] ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘0’ 6000
  • 65. 65 Addresses in Memory • When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is the address of the variable int x; float number; char ch; 2000 2002 2006 x number ch
  • 66. 66 Obtaining Memory Addresses • The address of a non-array variable can be obtained by using the address-of operator & int x; float number; char ch; cout << “Address of x is “ << &x << endl; cout << “Address of number is “ << &number << endl; cout << “Address of ch is “ << &ch << endl; x number ch 2000 2002 2006
  • 67. 67 What is a pointer variable? • A pointer variable is a variable whose value is the address of a location in memory. • To declare a pointer variable, you must specify the type of value that the pointer will point to, for example, int* ptr; // ptr will hold the address of an int char* q; // q will hold the address of a char
  • 68. 68 Using a Pointer Variable int x; x = 12; int* ptr; ptr = &x; NOTE: Because ptr holds the address of x, we say that ptr “points to” x 2000 12 x 3000 2000 ptr
  • 69. 69 int x; x = 12; int* ptr; ptr = &x; cout << *ptr; NOTE: The value pointed to by ptr is denoted by *ptr *: dereference operator 2000 12 x 3000 2000 ptr
  • 70. 70 int x; x = 12; int* ptr; ptr = &x; *ptr = 5; Using the Dereference Operator 2000 12 x 3000 2000 ptr 5 // changes the value at the address ptr points to 5
  • 71. 71 char ch; ch = ‘A’; char* q; q = &ch; *q = ‘Z’; char* p; p = q; Self –Test on Pointers 4000 A ch 5000 4000 q Z 6000 p 4000 // the rhs has value 4000 // now p and q both point to ch
  • 72. 72 ptr Using a Pointer to Access the Elements of a String ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘0’ char msg[ ] =“Hello”; char* ptr; ptr = msg; *ptr = ‘M’ ; ptr++; *ptr = ‘a’; msg 3000 3000 ‘M’ ‘a’ 3001
  • 73. 73 Reference Variables Reference variable = alias for another variable - Contains the address of a variable (like a pointer) - No need to perform any dereferencing (unlike a pointer) - Must be initialized when it is declared int x = 5; int &z = x; // z is another name for x int &y ; //Error: reference must be initialized cout << x << endl; -> prints 5 cout << z << endl; -> prints 5 z = 9; // same as x = 9; cout << x << endl; -> prints 9 cout << z << endl; -> prints 9
  • 74. 74 Why Reference Variables • Are primarily used as function parameters • Advantages of using references: – you don’t have to pass the address of a variable – you don’t have to dereference the variable inside the called function
  • 75. 75 Reference Variables Example #include <iostream.h> // Function prototypes (required in C++) void p_swap(int *, int *); void r_swap(int&, int&); int main (void){ int v = 5, x = 10; cout << v << x << endl; p_swap(&v,&x); cout << v << x << endl; r_swap(v,x); cout << v << x << endl; return 0; } void r_swap(int &a, int &b) { int temp; temp = a; (2) a = b; (3) b = temp; } void p_swap(int *a, int *b) { int temp; temp = *a; (2) *a = *b; (3) *b = temp; }