SlideShare a Scribd company logo
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.
Class and object C++.pptx
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
Class and object C++.pptx
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 (20)

OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3
Dr. SURBHI SAROHA
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
sidra tauseef
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
Rassjb
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
rumanatasnim415
 
Major terminologies in oop (Lect 2).ppt. Object oriented programming
Major terminologies in oop (Lect 2).ppt. Object oriented programmingMajor terminologies in oop (Lect 2).ppt. Object oriented programming
Major terminologies in oop (Lect 2).ppt. Object oriented programming
nungogerald
 
Introduction to Fundamental of Class.pptx
Introduction to Fundamental of Class.pptxIntroduction to Fundamental of Class.pptx
Introduction to Fundamental of Class.pptx
DawitTekie1
 
oopm 2.pdf
oopm 2.pdfoopm 2.pdf
oopm 2.pdf
jayeshsoni49
 
Introduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book NotesIntroduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book Notes
DSMS Group of Institutes
 
Unit_2_oop By Alfiya Sayyed Maam from AIARKP
Unit_2_oop By Alfiya Sayyed Maam from  AIARKPUnit_2_oop By Alfiya Sayyed Maam from  AIARKP
Unit_2_oop By Alfiya Sayyed Maam from AIARKP
mradeen946
 
Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++
jehan1987
 
CSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptx
CSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptxCSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptx
CSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptx
winebaldbanituze
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
Dennis Chang
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
Getachew Ganfur
 
Object Oriented Programming Examples with explanation
Object Oriented Programming Examples with explanationObject Oriented Programming Examples with explanation
Object Oriented Programming Examples with explanation
ulhaq18
 
Chapter 2 OOP using C++ (Introduction).pptx
Chapter 2 OOP using C++ (Introduction).pptxChapter 2 OOP using C++ (Introduction).pptx
Chapter 2 OOP using C++ (Introduction).pptx
FiraolGadissa
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
manomkpsg
 
05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx
ToranSahu18
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
02.adt
02.adt02.adt
02.adt
Aditya Asmara
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
Rassjb
 
Major terminologies in oop (Lect 2).ppt. Object oriented programming
Major terminologies in oop (Lect 2).ppt. Object oriented programmingMajor terminologies in oop (Lect 2).ppt. Object oriented programming
Major terminologies in oop (Lect 2).ppt. Object oriented programming
nungogerald
 
Introduction to Fundamental of Class.pptx
Introduction to Fundamental of Class.pptxIntroduction to Fundamental of Class.pptx
Introduction to Fundamental of Class.pptx
DawitTekie1
 
Introduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book NotesIntroduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book Notes
DSMS Group of Institutes
 
Unit_2_oop By Alfiya Sayyed Maam from AIARKP
Unit_2_oop By Alfiya Sayyed Maam from  AIARKPUnit_2_oop By Alfiya Sayyed Maam from  AIARKP
Unit_2_oop By Alfiya Sayyed Maam from AIARKP
mradeen946
 
Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++
jehan1987
 
CSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptx
CSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptxCSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptx
CSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptx
winebaldbanituze
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
Dennis Chang
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
Getachew Ganfur
 
Object Oriented Programming Examples with explanation
Object Oriented Programming Examples with explanationObject Oriented Programming Examples with explanation
Object Oriented Programming Examples with explanation
ulhaq18
 
Chapter 2 OOP using C++ (Introduction).pptx
Chapter 2 OOP using C++ (Introduction).pptxChapter 2 OOP using C++ (Introduction).pptx
Chapter 2 OOP using C++ (Introduction).pptx
FiraolGadissa
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
manomkpsg
 
05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx
ToranSahu18
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 

Recently uploaded (20)

The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Transformimet e sinjaleve numerike duke perdorur transformimet
Transformimet  e sinjaleve numerike duke perdorur transformimetTransformimet  e sinjaleve numerike duke perdorur transformimet
Transformimet e sinjaleve numerike duke perdorur transformimet
IndritEnesi1
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
gerogepatton
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
Axial Capacity Estimation of FRP-strengthened Corroded Concrete Columns
Axial Capacity Estimation of FRP-strengthened Corroded Concrete ColumnsAxial Capacity Estimation of FRP-strengthened Corroded Concrete Columns
Axial Capacity Estimation of FRP-strengthened Corroded Concrete Columns
Journal of Soft Computing in Civil Engineering
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Mohamed905031
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Class-Symbols for vessels ships shipyards.pdf
Class-Symbols for vessels ships shipyards.pdfClass-Symbols for vessels ships shipyards.pdf
Class-Symbols for vessels ships shipyards.pdf
takisvlastos
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
MODULE 6 - 1 VAE - Variational Autoencoder
MODULE 6 - 1 VAE - Variational AutoencoderMODULE 6 - 1 VAE - Variational Autoencoder
MODULE 6 - 1 VAE - Variational Autoencoder
DivyaMeenaS
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant ConversionStructural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Transformimet e sinjaleve numerike duke perdorur transformimet
Transformimet  e sinjaleve numerike duke perdorur transformimetTransformimet  e sinjaleve numerike duke perdorur transformimet
Transformimet e sinjaleve numerike duke perdorur transformimet
IndritEnesi1
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
gerogepatton
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Mohamed905031
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Class-Symbols for vessels ships shipyards.pdf
Class-Symbols for vessels ships shipyards.pdfClass-Symbols for vessels ships shipyards.pdf
Class-Symbols for vessels ships shipyards.pdf
takisvlastos
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
MODULE 6 - 1 VAE - Variational Autoencoder
MODULE 6 - 1 VAE - Variational AutoencoderMODULE 6 - 1 VAE - Variational Autoencoder
MODULE 6 - 1 VAE - Variational Autoencoder
DivyaMeenaS
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant ConversionStructural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Ad

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.
  • 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
  • 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; }