02. Classes and Objects
02. Classes and Objects
Oriented
Programming
Using
C ++
Abdul Wahab abdul_bu@yahoo.com
Lecturer
University of Science and Technology Bannu
1
Object
2
Class
A class is grouping of objects having identical properties, common
behavior and shared relationship.
Class: Car
Properties: Company, Model, Color and Capacity etc.
Action: Speed() and Break().
Class: Computer
Properties: Brand, Price, Processor Speed and Ram etc.
Action: Processing(), Display() and Printing().
The entire group of data and code of an object can be built as a user-
defined data type using class.
3
Access Specifiers
Private:
The private members of a class are accessible only by the member
functions or friend functions of the class.
Public:
The public members are accessible from any where in the program.
Protected:
The protected members of a class are accessible by the member
functions of the class and the classes which are derived from this class.
4
General Form of a Class
class class_name
{
private:
//private data and functions
public:
//public data and function
}object_list;
5
Declaring Objects
When objects are created only during that moment, memory is allocated
to them
int x, y;
char ch;
item a, b, *c;
6
Properties of Objects
It is individual
7
The class has a mechanism to prevent direct access to its members,
which is the central idea of object oriented programming
8
Accessing Class Members
9
Example
10
The Public Keyword
The keyword public can be used to allow object to access the member
variables of a class directly
class Sample
{
public:
// Public Members
};
11
Example
12
The Private Keyword
13
Example
class item void item :: set_show()
{ {
codeno=123;
int codno;
price=150.00;
float price; qty=15;
int qty; cout<< codno <<endl;
public: cout<< price <<endl;
cout<< qty <<endl;
void set_show();
}
};
void main()
{
clrscr();
item a;
a.set_show();
}
14
Output
123
150.00
15
15
The Protected Keyword
It is used in inheritance
16
Access Mechanism
17
Defining Member Functions
The member functions must be declared inside the class. They can be
defined:
18
Member Function Inside the Class
A. In Public Section:
class item{
int codno; int main()
float price; {
int qty; clrscr();
public: item one;
void show() one.show();
{
codeno=125; return 0;
price=150.00; }
qty=200;
cout<<“Code No = ”<< codno;
cout<<“Price = ”<< price;
cout<<“Quantity = ”<< qty;
}
};
19
Member Function Inside the Class
B. In Private Section
class item{
int codno; int main()
float price; {
int qty;
clrscr();
void values()
{ item one;
codeno=125; // one.values(); /// Not Accessible
price=150.00; one.show();
qty=200;
}
public: return 0;
void show() }
{
values();
cout<<“Code No = ”<< codno;
cout<<“Price = ”<< price;
cout<<“Quantity = ”<< qty;
}
};
20
Member Function Outside the Class
class item{
int codno;
float price;
int main()
int qty;
{
public:
clrscr();
void show();
item one;
};
one.show();
21
Have a Nice Day!