Classes and Objects

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 39

CLASSES AND OBJECTS

C Structures Revisited
• In C, structures provide a method for packing together data of
different types.
• A structure is a convenient tool for handling a group of logically
related data items.
• It is a user-defined data type with a template that serves to define its
data properties.
• Once a structure has been defined, we can create variables of that
type using declarations similar to the built-in type declarations.
• For example,
struct student
{
char name[20];
int roll_number;
float total_marks;
};
• The identifier student, which is referred to as structure name or
structure tag, can be used to create variables of type student.
Example:
struct student A;
• A is a variable of type student and has three member variables as
defined by the template.
• Member variables can be accessed using the dot or period operator.
Limitations of C Structure
• The standard C does not allow the struct data type to be treated like
built-in types.
• C structures do not permit data hiding. Structure members can be
directly accessed by the structure variables by any function anywhere
in their scope.
Specifying a Class
• A class is a way to bind the data and its associated functions together.
It allows the data to be hidden from external use.
• A class specification has two parts:
1. Class declaration
2. Class function definitions
• The class declaration describes the type and scope of its members.
• The class function definitions describe how the class functions are
implemented.
• The general form of a class declaration is:
class class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
Data hiding in classes
A Simple class example
class item
{
int number;
float cost;
public:
void getdata(int a, float b);
void putdata(void);
};
• Usually, some meaningful name is given to a class.
Creating Objects
• Once a class has been declared, variables of class type can be created by using
the class name. for example,
item x; //memory for x is created
• The above statement creates a variable x of type item. In C++, the class variables
are known as objects.
• Objects can also be created when a class is defined by placing their name
immediately after the closing brace, just like structures.
class item
{
…..
…..
…..
} x, y, z;
Accessing class members
• The private data of a class can be accessed only through the member
functions of that class. For example, the function call statement
x.getdata(100, 75.5);
is valid and assigns the value 100 to number and 75.5 to cost of the
object x by implementing the getdata() function. The assignments
occur in the actual function as shown below.
void item:: getdata(int a, float b)
{
number = a;
cost = b;
}
• A variable declared as public can be accessed by the objects directly. For example,
class xyz
{
int x;
int y;
public:
int z;
};
int main()
{
xyz p;
p.x = 0; // error, x is private
p.z = 10 // Ok, z is public
Defining member functions
• Member functions can be defined in two places:
• Outside the class definition.
• Inside the class definition.
• Irrespective of the place of definition, the function should perform
the same task.
Outside the Class Definition
• An important difference between a member function and a normal
function is that a member function incorporates a membership
‘identity label’ in the header which tells the compiler which class the
function belongs to.
• The general form of a member function definition is:
return-type class-name:: function-name (argument declaration)
{
Function body
}
Outside the Class Definition Example
class item void item:: getdata(int a, float b)
{ {
int number; number = a;
float cost; cost = b;
public: }
void getdata(int a, float b); void item:: putdata (void)
void putdata(void); {
}; cout<<“number:”<<number<<“\n”;
cout<<“cost:”<<cost<<“\n”;
}
Inside the Class Definition
• When a function is defined inside a class, it is treated as an inline
function. Therefore, all restrictions and limitations that apply to an
inline function are also applicable here.
• Normally only small functions are defined inside the class definition.
class item //member function definition
{ void item:: getdata(int a, float b)
int number; {
float cost; number = a; //private variables directly used
public: cost = b;
void getdata(int a, float b); }
// Function defined inside the class Int main()
void putdata(void) {
{ item x; // create object x
cout<<“number:”<<number<<“\n”; x.getdata (100, 299.95);
cout<<“cost:”<<cost<<“\n”; x.putdata();
} return 0;
}
};
Nesting of Member Functions
• A member function can be called by using its name inside another
member function of the same class. This is known as nesting of the
member functions.
#include<iostream> int set :: largest(void)
using namespace std; {
class set if (m>=n)
{ return m;
int m, n; else
public: return n;
void input(void); }
void display(void); void set :: input (void)
int largest(void); {
}; cout<<“Input values of m and n” <<“\n”;
cin>>m>>n;
}
void set :: display (void)
{
cout<<“largest value = ”<< largest() <<“\n”;
\\ calling member function
}
int main()
{
set A;
A.input();
A.display();
return 0;
}
Private Member Functions
• Although it is normal practice to place all the data items in a private
section and all the member functions in public, some situations may
require certain functions to be hidden from the outside calls.
• Tasks such as deleting an account in a customer file, or providing
increment to an employee are events of serious consequences and
therefore the functions handling such tasks should have restricted
access.
• Such functions can be placed in the private section.
• A private member function can be called by another function that is a
member of its class.
• Even an object cannot invoke a private function using the dot
operator.
• Consider the class defined below. s1.read()
class sample • is illegal. However, the read() can be
{ called by the function update() to
update the value of m.
int m;
void sample::update(void)
void read(void);
{
public:
read();
void update(void);
// simple call; no object used
void write(void);
}
};
• If s1 is an object of sample, then
Arrays within a class
• The arrays can be used as member variables in a class. The following
class definition is valid.
const int size = 10; // provides value for array size
class array
{
int a[size]; // a is int type array
public:
void setval(void);
void display(void);
};
#include<iostream> void getitem(void);
using namespace std; void displaySum(void);
const m =50; void remove(void);
void displayItems(void);
class ITEMS
};
{
void ITEMS :: getitem(void)
int itemCode[m]; {
float itemPrice[m]; cout<<“Enter Itemcode:”;
int count; cin>>itemcode[count];
public: cout<<“Enter item cost:”;
void CNT(void) cin>>itemPrice[count];
count++;
{ count = 0;}
}
void ITEMS :: displaySum(void) void ITEMS :: displayItems(void)
{ {
float sum = 0; cout<<“\nCode Price\n”;
for(int i = 0; i<count; i++) for(int i = 0; i<count; i++)
sum = sum + itemPrice[i]; {
cout<<“\nTotal value: ” << cout<<“\n”<<itemCode[i];
sum<<“\n”;
cout<<“ “<<itemPrice[i];
}void ITEMS :: remove(void)
}
{
cout<<“\n”;
int a;
}
cout<<“Enter item code: “;
int main()
cin>>a;
for(int i = 0; i<count; i++) {
if(itemCode[i] == a) ITEMS order;
itemPrice[i] = 0; order.CNT();
} int x;
do
{
cout<<“\nYou can do the following:”
<<“Enter appropriate number \n”;
cout<<“\n1: Add an item ”;
cout<<“\n2: Display total value ”;
cout<<“\n3: Delete an item ”;
cout<<“\n4: Display all items ”;
cout<<“\n5: Quit ”;
cout<<“\nWhat is your option? ”;
cin>>x;
switch(x)
{
case 1: order.getitem(); break;
case 2: order. displaySum(); break;
case 3: order. remove(); break;
case 4: order.displayitems(); break;
case 5: break;
default: cout<<“Error in input; try again\n”;
}
} while (x!= 5);
return 0;
}
Memory allocation for objects
• The memory space for objects is allocated when they are declared
and not when the class is specified but, the member functions are
created and placed in the memory space only once when they are
defined as a part of a class specification.
• Since all objects belonging to that class use the same member
functions, no separate space is allocated for member functions when
the objects are created. Only space for member variables is allocated
separately for each object.
• Separate memory locations for the objects are essential because the
member variables will hold different data values for different objects.
Static Data Members
• A data member of a class can be static. A static member has certain
special characteristics. These are:
• It is initialized to zero when the first object of its class is created. No other
initialization is permitted.
• Only one copy of that member is created for the entire class and is shared by
all the objects of that class, no matter how many objects are created.
• It is visible only within the class, but its lifetime is the entire program.
• Static variables are normally used to maintain values common to the
entire class. For example, a static data member can be used as a
counter that records the occurrences of all the objects.
#include<iostream>
using namespace std;
class item
{
static int count; int number;
public:
void getdata(int a)
{
number = a;
count++;
}
void getcount(void)
{
cout << "count: ";
cout << count << "\n";
}
};
int item :: count; // definition of static data member
int main()
{
item a,b,c;
a.getcount(); // count is initialized to zero
b.getcount(); //display count
c.getcount();
a.getdata(100); // getting data into abject o
b.getdata(200); // getting data into object b
c.getdata(300): // getting data into object c

cout << "After reading data" << "\n";


a.getcount(); //display count
b.getcount();
c.getcount();
return 0;
}
• The output of the program:
count: 0
count: 0
count: 0
After reading data
count: 3
count: 3
count: 3
Sharing of a static data member
• The type and scope of each static member variable must be defined
outside the class definition. This is necessary because the static data
members are stored separately rather than as a part of an object.
• Static variables are like non-inline member functions as they are
declared in a class declaration and defined in the source file.
• While defining a static variable, some initial value can also be
assigned to the variable as shown below
int item :: count =10;
Static member Functions
• A member function that is declared as static has the following
properties:
• A static function can have access to only other static members (functions or
variables) declared in the same class.
• A static member function can be called using the class name (instead of its
objects) as follows:
Class-name :: function-name;
#include<iostream>
using namespace std;
class test
{
int code;
static int count;
public:
void setcode(void)
{
code = ++count;
}
void showcode(void)
{
cout<<“Object number: “<< code <<“\n”;
}
static void showcount(void)
{
cout<< “count: ” << count <<“\n”;
}
};
int test :: count;
int main()
{
test t1, 2;
t1.setcode();
t2.setcode();
test :: showcount (); // accessing static function
test t3;
t3.setcode();
test :: showcount();
t1.showcode();
t2.showcode();
t3.showcode();
return 0;
}
• Output of the program
count: 2
count: 3
object number: 1
object number: 2
object number: 3

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy