13 Classes & Objects
13 Classes & Objects
PDPU
1
REVISITING STRUCTURES…
4
EXTENSIONS TO STRUCTURES…
6
A CLASS SPECIFICATION…
7
THE GENERAL FORM OF A CLASS
DECLARATION …
class class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
8 };
THE GENERAL FORM OF A CLASS
DECLARATION …
class is a keyword.
It specifies an abstract data of type
class_name
Class body contains variables and
functions.
Variable and functions are known as class
members.
Class members are grouped under two
9 sections: private & public.
REPRESENTATION OF A CLASS
circle
CLASS: circle
DATA setradius( )
radius
area
calc_area( )
FUNCTIONS
setradius( )
calc_area( )
10
EXAMPLE…
DECLARING A CLASS & ITS MEMBERS
void main()
{
int r = 5; circle c1; c1.setradius(r);
cout << c1.calc_area() << endl;
// cout << "The value of radius of c1 is " << c1.radius;
// error: not accessible outside circle.
// cout << setradius(10);
// again an error : setradius ( ) should have prototype.
getch();
12 }; Program object1.cpp
UNDERSTANDING EXAMPLE…
15
ANOTHER METHOD OF CREATING
OBJECTS…
class circle
{
…
…
} c1, c2, c3, c[3];
16
GENERAL FORMAT TO ACCESS
CLASS MEMBERS
17
Exercise 1…
Create a class called student_data containing following
information only.
Roll No.,
name,
marks of physics, maths and Chemistry, and
total.
18
Exercise 2…
19
Exercise 3…
Create a class to specify data of customers in a bank.
The data to be stored is: Account Number, Name,
Balance in account.
Assume maximum 10 customers in the bank.
21
DEFINING MEMBER FUNCTION
OUTSIDE THE CLASS DEFINITION
22
DEFINING MEMBER FUNCTION
OUTSIDE THE CLASS DEFINITION
class circle
{
private:
int radius;
float area;
public:
void setradius(int);
float calc_area(void);
23 };
DEFINING MEMBER FUNCTION
OUTSIDE THE CLASS DEFINITION
void circle::setradius(int r)
{
radius = r;
cout << "The value of radius is set to " <<
radius << endl;
area = calc_area();
cout << area << endl;
}
24
DEFINING MEMBER FUNCTION
OUTSIDE THE CLASS DEFINITION
float circle::calc_area(void)
{
area = 22.0/7*radius*radius;
return area;
}
25 Program object2.cpp
MEMORY ALLOCATION FOR
OBJECTS
27
OBJECTS OF CLASS CIRCLE
CREATED…
class circle
{
…
…
} c1, c2, c3;
28
MEMORY ALLOCATION FOR
OBJECTS
calc_area ( )
MEMORY CREATED WHEN
FUNCTIONS DEFINED
c1 c2 c3
30
OBJECTS AS FUNCTION ARGUMENTS
… PASSED BY VALUE…
class CLASS-NAME
{
…
…
public:
…
…
friend return-type function-name (arg);
34 }; Program obect4.cpp
FRIENDLY FUNCTIONS.
FEW POINTS…
class X class Y
{ {
… …
int func1( ); friend int X::func1();
}; };
37
FRIENDLY FUNCTIONS.
FEW POINTS… (FRIEND CLASS)
39 Program obect5.cpp
SUMMARY…
41
SUMMARY…
42