Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
3 views17 pages

Topic 6 - Classes and Objects

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views17 pages

Topic 6 - Classes and Objects

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

1

TOPIC 6: CLASSES AND OBJCETS

CLASS: A class is a group of objects that share common properties and relationships .When we
define a class, we are creating a new abstract data type that can be treated like any other built in data
type.
Generally a class specification has two parts:-
a) Class declaration
b) Class function definition
the class declaration describes the type and scope of its members. The class function definition
describes how the class functions are implemented.

Syntax:-
class class-name
{
private:
variable declarations; function declaration ;
public:
variable declarations; function declaration;
};

IMP. POINTS
1.The members that have been declared as private can be accessed only
from within the class.
2. On the other hand , public members can be accessed from outside the class also. The data hiding is
the key feature of oops.
3. The use of keywords private is optional by default, the members of a class are private.
4. The variables declared inside the class are known as data members and the functions are known as
members functions.
5. Only the member functions can have access to the private data members and private functions.
6. However, the public members can be accessed from the outside the class. The binding of data and
functions together into a single class type variable is referred to as encapsulation.

CREATING OBJECTS

Once a class has been declared we can create variables of that type by using the class name.
Syntax: classname objectname;

ACCESSING CLASS MEMBER:


The private data of a class can be accessed only through the member functions of that class.
Syntax:
Object name.function name(actual arguments);

DEFINING MEMBER FUNCTION:

Member can be defined in two places


• Inside the class function
• Outside the class definition

TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS


2

INSIDE THE CLASS DEFINATION

Another method of defining a member function is to replace the function declaration by the actual
function definition inside the class .
Example:
class item
{
public:
Int number;
float cost;

void getdata (int a ,float b)


{

}
void putdata(void) // inside the class definition
{
}
};

OUTSIDE THE CLASS DEFlNAT1ON

Member function that are declared inside a class have to be defined separately outside the class.Their
definition are very much like the normal functions.
An important difference between a member function and a normal function is that a member function
incorporates a membership. Identify label in the header. The ‘label’ tells the compiler which class the
function belongs to.

Syntax:
return type class-name::function-name(argument declaration )
{
function-body
}

Example:
class item
{
public:
Int number;
float cost;
void getdata (int ,int);
void putdata();
};
void item::getdata(int a ,int b)
{
}
void item::putdata()
{
}

TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS


3

The member ship label class-name :: tells the compiler that the function function - name belongs to
the class class-name . That is the scope of the function is restricted to the class- name specified in the
header line. The :: symbol is called scope resolution operator.

The member function have some special characteristics that are often used in the program
development.
• Several different classes can use the same function name. The "membership label" will
resolve their scope, member functions can access the private data of the class
.A non member function can't do so.
• A member function can call another member function directly, without using the dot operator.

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 member functions.

PRIVATE MEMBER FUNCTIONS

Although it is a normal practice to place all the data items in a private section and all the functions in
public, some situations may require contain functions to be hidden from the outside calls.
A private member function can only be called by another function that is a member of its class.
Even an object cannot invoke a private function using the dot operator.

EXAMPLES OF CLASSES AND OBJECTS

1. /*Define a class student with the following specifications:


private:
rollno-int
name -char array size [20]
marks- int array size [5]
calculate()-To calculate and return %of the student back to the calling function
public:
read()-Accept marks of a student in 5 subjects
input()-accepts name and rollno of the student from the user
display()-displays all the data members on the screen. */

#include <iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class student
{
int rollno,marks[5];
char name[30];
float calculate();
public: void read();
void input();
void display();
};
void student::input()
TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS
4

{
cout<< "enter the roll no";
cin>>rollno;
cout<<"enter name";
cin>>name;
}
void student::read()
{
cout<< "enter the marks in 5 subjects";
for(int i=0;i<5;i++)
cin>>marks[i];
}

float student::calculate()
{
int s=0;
for(int i=0;i<5;i++)
s=s+marks[i];
return (s/5.0);
}

void student::display()
{
puts(name);
cout<<endl<<rollno<<endl;
cout<<calculate();
}
int main()
{
student a;
a.input();
a.read();
a.display();
getch();
}

2. /*Define a class test in C++ with the following specification


private:
tcode, noc(no of candidates),centres –(int)
place- char [20]
count()-to calculate and return the number of centres as (no of candidates/100+1)
enter()-which accepts values for tcode ,place, noc, centres from the user.
public:
show()-which displays all data values on the screen.
*/
#include <iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class test
{ int tcode,noc,centres;
TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS
5

char place[30];
float count();
public: void enter();
void display();
};
void test::enter()
{ cout<< "enter the tcode,noc";
cin>>tcode>>noc;
cout<<"enter place";
cin>>place;
}

float test::count()
{
float k;
k=noc/100.0+1;
return k;
}

void test::display()
{
cout<<tcode<<endl<<noc<<endl<<count()<<endl;
puts(place);
}
int main()
{
test a;
a.enter();
a.display();
getch();
}

3. /*Define a class competition in C++ with the following specification


private:
eventno, score -(int)
title- char [20],qualified
public:
input()-to take input for eventno, title and score.
award()-to award qualified as 'y' if score is more than cut off score(int) passed as argument to this
function else award 'N'.
show()-which displays all data values on the screen.*/

#include <iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class competition
{
int eventno,score;
char title[30],qualified;
public: void input();
TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS
6

void award(int);
void show();
};
void competition::input()
{cout<< "enter eventno and score";
cin>>eventno>>score;
cout<<"enter title";
cin>>title;
}

void competition::award(int x)
{ if(score>x)
qualified='Y';
else
qualified='N';
}

void competition::show()
{
cout<<eventno<<endl<<score<<endl<<qualified<<endl;
puts(title);
}

int main()
{int cs;
cout<<"enter cutoff score";
cin>>cs;
competition a;
a.input();
a.award(cs);
a.show();
getch();
}

4. /*Define a class applicant in C++ with the following specification


private:
ano(long)
name- char [20],grade
float agg;
grademe()-to find grade as per the agg marks obtained by a student.
agg grade
>=80 A
Less than 80 and >=65 B
Less than 65 and >=50 C
Less than 50 D
public:
enter()-to take input for ano, name and agg.
result()-which displays all data values on the screen.
*/

TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS


7

#include <iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class applicant
{
long ano;
char name[30],grade;
float agg;
void grademe();
public: void enter();
void result();
};
void applicant::enter()
{
cout<< "enter ano and agg";
cin>>ano>>agg;
cout<<"enter name";
cin>>name;
}

void applicant::grademe()
{ if(agg>=80)
grade='A';
else if(agg>=65)
grade='B';
else
if(agg>=50)
grade='C';
else
grade='D';
}
void applicant::result()
{
grademe();
cout<<ano<<endl<<agg<<endl<<grade<<endl;
puts(name);
}

int main()
{
applicant a;
a.enter();
a.result();
getch();
}

5. /*Define a class tour in C++ with the following specification


private:
noa(no of adults),nok(no of kids),km(kilometers),-int
tcode-char [20]
TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS
8

float total_fare
assignfare()-which calculates and assigns the values of the data member total_fare as follows:
For each adult
fare km
500 >=1000
300 <1000 & >=500
200 <500
For each kid the fare will be 50% of the fare mentioned.
public:
enter()-to take input for tcode,noa,nok, and km
show()-which displays all data values on the screen.
Note: eg: if km=850,noa=2 and nok=3 then the
total_fare=2X300+3X150=1050*/

#include <iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class tour
{
int noa ,nok,km;
char tcode[30];
float total_fare;
void assignfare();

public:
void enter();
void show();
};
void tour::enter()
{
cout<< "enter noa,nok and km";
cin>>noa>>nok>>km;
cout<<"enter tcode";
cin>>tcode;
assignfare();
}

void tour::assignfare()
{ if(km>=1000)
total_fare=500*noa+250*nok;

else
if(km>=500)
total_fare=300*noa+150*nok;
else
total_fare=200*noa+100*nok;
}
void tour::show()
{
cout<<tcode<<endl<<noa<<endl<<nok<<endl<<km<<endl<<total_fare<<endl;
TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS
9

puts(tcode);
}
int main()
{
tour a;
a.enter();
a.show();
getch();
}

6. /*Define a class carrental in C++ with the following specification


private:
carid(long int)
cartype- char [20]
float rent;
assignrent()-to assign the following values for rent as per the given cartype
cartype rent
small 1000
van 800
suv 2500
public:
getcar()-to take input for carid, cartype and call assignrent() to assign the rent.
showcar()-which displays all data values on the screen.
*/

#include <iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class carrental
{long int carid;
char cartype[20];
float rent;
void assignrent();
public:
void getcar();
void showcar();
};
void carrental::getcar()
{ cout<< "enter carid";
cin>>carid;
cout<<"enter car type";
cin>>cartype;
assignrent();
}

void carrental::assignrent()
{ if(strcmp(cartype,"small")==0)
rent=1000;
else
if(strcmp(cartype,"van")==0)
TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS
10

rent=800;
else
rent=2500;
}
void carrental::showcar()
{
cout<<carid<<endl<<rent<<endl;
puts(cartype);
}
int main()
{
carrental a;
a.getcar();
a.showcar();
getch();
}

EXAMPLES OF ARRAY OF OBJECTS

/*1. Define a class Item in C++ with following description:


Private:
" icode- type integer
" iname- Character array size 20
" quantity - type float
" unit_price-type float
Public:
" A member function readvalues()- to accept the values for Icode,Name,Qty and Price.
" A member function showvalues()- to calculate total as total=Qty*Price. And display all the
data members on the screen in the following manner.
************************************************************************Srno
Itemcode Quantity Price Total
1
2

************************************************************************

Write a function main() to declare an array of objects and call necessary functions for N items where
N is the no of items to be purchased.
*/

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
#include<string.h>
#include<stdio.h>
class item
{
int icode,quantity;
char iname[20];
float unit_price;
TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS
11

public:
void read_values();
void show_values(int);
};
void item::read_values()
{
cout<<"Enter icode";
cin>>icode;
cout<<"\nEnter iname";
cin>>iname;
cout<<"\nEnter quantity";
cin>>quantity;
cout<<"\nEnter unit_price";
cin>>unit_price;
}

void item::show_values(int t)
{
float total;
total=quantity*unit_price;
cout<<setw(5)<<t<<setw(15)<<icode<<setw(20)<<iname<<setw(10)<<quantity<<setw(10)<<unit_p
rice<<setw(10)<<total<<endl;
}
int main()
{
int n,i,k;
item a[10]; // array of objects created
cout<<"Enter the no. of entries";
cin>>n;
for(i=0;i<=n-1;i++)
a[i].read_values();
for(i=0;i<=79;i++)
cout<<"*";
cout<<"\n";
cout<<setw(5)<<"Sr. no."<<setw(15)<<"Item Code"<<setw(20)<<"Item
Name"<<setw(10)<<"Quantity"<<setw(10)<<"Unit Price"<<setw(10)<<"Total"<<endl;
for(i=0;i<=79;i++)
cout<<"*";
cout<<"\n";
for(i=0;i<=n-1;i++)
a[i].show_values(k++);
for(i=0;i<=79;i++)
cout<<"*";
getch();
}

2. /*2. Define a class Book in C++ with following description:


Private:
" Bno- type integer
" Tiltle- Character array size 20
" Price - type float
TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS
12

" A function Totalcost()- to compute and returns the total cost to be paid as price x N_copies
where N_copies is the number of copies passed as argument to the function.
Public:
" A member function input()- to accept the values for Bno,Title and Price.
" A member function purchase()- to take input for N_copies and display total cost by calling
function Totalcost()
Write a function main() to declare an array of objects and call necessary functions for N books where
N is the no of books to be purchased.
*/

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
#include<string.h>
#include<stdio.h>
class book
{
int bno;
char title[20];
float price;
float totalcost(int);
public:
void input();
void purchase();
};
void book::input()
{
cout<<"Enter bno";
cin>>bno;
cout<<"\nEnter title";
cin>>title;
cout<<"\nEnter price";
cin>>price;
}
float book::totalcost(int t)
{
float to;
to=price*t;
return to;
}
void book::purchase()
{int cop;
cout<<"enter no of copies";
cin>>cop;
cout<<"total cost= "<<totalcost(cop);
}
int main()
{
int n,i;
book a[10];
cout<<"Enter the no. of books";
TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS
13

cin>>n;
for(i=0;i<=n-1;i++)
a[i].input();
for(i=0;i<=n-1;i++)
a[i].purchase();
getch();
}
EXAMPLES OF OBJCETS AS FUNCTION ARGUMENTS

1. /*1. Define a class Distance in C++ with following description:


Private:
" Feet- type integer
" Inches- type integer
Public:
" A function read()- to read values for feet and inches
" A member function show()- to display all data members on screen.
" A member function sum()- which accepts 2 objects of class distance as parameters,calculates
sumof corresponding data members and displays the result on the screen.

Write function main() to create 3 objects d1,d2 and calculate d3 as sum of d1 and d2.
Note:12"=1 feet
Eg: if d1=5 ft 8" and d2=7ft 5" then d3=13ft 1"
*/
#include <iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class distance
{
int feet,inches;
public:
void read();
void show();
void sum(distance,distance);
};
void distance::read()
{
cout<<"enter values for feet and inches";
cin>>feet>>inches;
}
void distance::show()
{ cout<<feet<<" "<<inches;
}
void distance::sum(distance a,distance b)
{
inches=a.inches+b.inches;
feet=a.feet+b.feet+inches/12;
inches=inches%12;
}
int main()
{
TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS
14

distance d1,d2,d3;
d1.read();
d2.read();
d1.show();
d2.show();
d3.sum(d1,d2); // passing objects as function arguments
d3.show();
getch();}

2. /*2. Define a class Time in C++ with following description:


Private:
" hours- type integer
" mins- type integer
" seconds-type integer
Public:
" A function read()- to read values for hours, mins and seconds
" A member function show()- to display all data members on screen.
" A member function sum()- which accepts 2 objects of class Time as parameters,calculates the
total time and displays the result on the screen.

Write function main() to create 3 objects t1,t2 and calculate t3 as sum of d1 and d2.
Note:60 seconds=1 min
60 min=1 hr
Eg: if t1= 5 hrs 35 min 50 seconds and t2= 6 hrs 30 min 20 seconds then t3=12 hrs 6 min 10 seconds
*/

#include <iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class time
{
int hours,mins,seconds;
public:
void read();
void show();
void sum(time,time);
};
void time::read()
{
cout<<"enter values for hours mins and seconds";
cin>>hours>>mins>>seconds;
}
void time::show()
{ cout<<hours<<" "<<mins<<" "<<seconds;
}
void time::sum(time a,time b)
{

seconds=a.seconds+b.seconds;
mins=a.mins+b.mins+seconds/60;
TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS
15

seconds=seconds%60;
hours=a.hours+b.hours+mins/60;
mins=mins%60;
}

int main()
{ time t1,t2,t3;
t1.read();
t2.read();
t1.show();
t2.show();
t3.sum(t1,t2);
t3.show ();
getch();
}

EXAMPLES OF FUNCTION RETURNING AN OBJECT


1. Define a class weight with the following specifications.
private: kilogram, gram of type integer
public: function getdata()- to accept values for kilogram and gram from the user.
function putdata()- to display the values of kilogram and gram.
function sum_weight()- which accept 2 objects as its parameters, calculates total kilograms and grams
in the object and returns the object back to the calling function.
write function main () to create 3 objects w1,w2 and w3 where w3 must call sum_weight() and must
have total kilograms and grams.

#include<iostream>
using namespace std;
class weight {
int kilogram;
int gram;
public:
void getdata ();
void putdata ();
weight sum_weight (weight,weight) ;
};
void weight :: getdata()
{
cout<<"/nKilograms:";
cin>>kilogram;
cout<<"Grams:";
cin>>gram;
}
void weight :: putdata ()
{
cout<<kilogram<<" Kgs. and"<<gram<<" gros.\n";
}
weight weight :: sum_weight(weight w1,weight w2)
{
weight temp;
TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS
16

temp.gram = w1.gram + w2.gram;


temp.kilogram=w1.kilogram+w2.kilogram;
temp.kilogram=temp.kilogram+temp.gram/1000;
temp.gram=temp.gram%1000;
return(temp);
}
int main () {
weight w1,w2 ,w3;
cout<<"Enter weight in kilograms and grams\n";
cout<<"\n Enter weight #1" ;
w1.getdata();
cout<<" \n Enter weight #2" ;
w2.getdata();
w3=w3.sum_weight(w1,w2);
cout<<"/n Weight #1 = ";
w1.putdata();
cout<<"Weight #2 = ";
w2.putdata();
cout<<"Total Weight = ";
w3.putdata();

}
2. Define class complex with the following specification
private: x,y type integer
public: function input() which accepts real part and imaginary part passed as arguments
function sum() to accept 2 objects as its arguments and calculates sum of two complex numbers and
returns the object back to the calling function.
function show() which accepts 1 object as its argument and displays the data members (as complex
number)
on screen
write function main() to create 3 objects a ,b and c , where c must call function sum() and must have
addition of complex numbers.

#include<iostream>
using namespace std;
class complex // x+yi form
{
float x; // real part
float y; // imaginary part
public:
void input(int,int);
complex sum(complex, complex);
void show(complex);
};

void complex::input(int real, int img)


{
x=real;
y=img;
TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS
17

complex complex::sum(complex c1, complex c2)


{
complex c3; // in this statement object c3 is created
c3.x=c1.x+c2.x;
c3.y=c1.y+c2.y;
return(c3); // returns object c3
}
void complex:: show(complex c)
{
cout<<c.x<<"+"<<c.y<<"i\n";
}
int main()
{
complex a,b,c;
a.input(3.1,5.65);
b.input(2.75,1.2);
c=c.sum(a,b);
cout<<"a=";
a.show(a);
cout<<"b=";
b.show(b);
cout<<"c=";
c.show(c);
}

TOPIC 6-CLASSES AND OBJECTS TR. ADITI P. NAIK, DBHSS

You might also like