OOP Chapter 2.1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

OOP Chapter 2 Ali Karim Sir

Chapter 2
Classes & Objects
Syllabus:
2.1. Class & Object: Introduction, 2.2. Static data members,
specifying a class, access specifies, Static member function
Defining member functions, Friend Function
Creating Objects, 2.3. Array of Objects,
Memory allocations for objects Object as function arguments.
-------------------------------------------------------------------------------------------------------------------------
2.1 Class & Object
Q Define the following terms: 1) Object 2) Class (2m)
Ans:
Classes:
A class is the collection of related data and function under a single name. A class is collection
of object of similar type. The entire set of data and code of an object can be made a user-defined data
type with the help of class.
Eg. class Employee
{

..
};
Objects:
Objects are the basic run time entities in an object-oriented system. They may represent a
person, a place, a bank account, a table of data or any item that the program has to handle. When a
program is executed, the objects interact by sending messages to one another.
Eg. void main()
{
Employee e;


}

Q Define class with its syntax. (Class definition – 1 Mark, Syntax – 1 Mark)
Ans:
Definition: A class is the collection of related data and function under a single name. A class is
collection of object of similar type. The entire set of data and code of an object can be made a user-
defined data type with the help of class.
Syntax:
class class_name
{
private:
Variable declarations;
Function declarations;
public:
Variable declarations;
Function declarations;
};

9220990566 CODINGBOSS YOUTUBE CHANNEL 1


OOP Chapter 2 Ali Karim Sir

Q How many ways we can define member function in class? Give it’s syntax. (Out Side Class
Definition - 2 Marks; Inside Class definition - 2 Marks)
Ans: Member functions can be defined in two ways:
• Outside class definition
• Inside class definition

Outside class definition:


Member functions that are declared inside class have to be defined separately outside class.
Their definitions are as simple as normal function definition. They should have function header &
body.
Difference between member function & normal function is that member function incorporates
membership “identity label” in header

General form of member function definition is as:


class class_name
{………
public:
return_type function_name(argument(s));
};

return-type class-name:: function-name(argument(s))


{
function body
}

Membership label class-name:: tell complier that function-name belongs to class class-name.
This is scope of function restricted to class-name specified in header line.
Scope resolution operator (::) is used.
For example member functions getdata() & putdata() of class item can be coded as follows:

void item :: getdata(int a, float b)


{
number =a;
cost= b;
}

Inside Class Definition:


This is method of defining member function is that member function declaration are replaced by actual
function definition inside the class
For example item class can be defined as:

class item
{
int number; //variable declaration
float cost; // private by default
public:
void getdata(inta, float b); //function declaration

9220990566 CODINGBOSS YOUTUBE CHANNEL 2


OOP Chapter 2 Ali Karim Sir

void putdata () // function definition


{
cout<<number<<”\n”;
cout<<cost;
}
};

2.2 Static data members


Q. Describe characteristic of static data member.
Ans: A data member of a class can be qualified as static.
Syntax: static datatype variable_name;
Eg: static int RateOfInterest
➢ 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.

int class_name :: static_variable; //definition of 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.

Example:
#include<iostream.h>
#include<conio.h>
class item
{
static int count;
int number ;
public:
void getdata(int a)
{
number =a;
count ++;
}

void getcount()
{
cout <<"count:";
cout << count <<"\n";
}
};

int item :: count; //definition of 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. */
9220990566 CODINGBOSS YOUTUBE CHANNEL 3
OOP Chapter 2 Ali Karim Sir

void main()
{
item a, b, c; //count is initialized to zero
clrscr();
a.getcount(); //display count
b.getcount();
c.getcount();

a.getdata(100); //getting data into object a


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( );
getch();
}

/*The static variable count is initialized to zero when the objects are created. The count is incremented
whenever the data is read into an object. Since, the data is read into objects three times, the variable
count is incremented three times. Because there is only one copy of count shared by all the three
objects. All the three output statements cause the value 3 to be displayed */

9220990566 CODINGBOSS YOUTUBE CHANNEL 4


OOP Chapter 2 Ali Karim Sir

Q. Write a program to define a class having data member principle, duration & rate-of-interest.
Declare rate-of- interest as static member variable. Calculate the simple interest & display it for
one object. (Class declaration – 2 Marks, Calculation Function – 1 Mark, Display data function –
1 Mark)
Ans:
//static data member rate-of- interest.
#include<iostream.h>
#include<conio.h>
class SI
{
float principle;
int duration;
static int rate_of_interest;
public:
void get()
{
cout<<“\n ***get()*** ”;
cout<<"\n Enter the principle: ";
cin>> principle;
cout<<"\n Enter the duration: ";
cin>>duration;
cout<<"\n...........................\n";
}

void put()
{
cout<<“\n ***put()***”;
cout<<"\n The principle is: "<< principle <<"Rs \n";
cout<<"\n The duration is: "<<duration<<"yrs \n";
cout<<"\n The rate of interest is: "<<rate_of_interest<<"% \n";
cout<<"\n The simple interest is: "<<(principle*rate_of_interest*duration)/100<<"Rs \n";
cout<<"\n________________________________\n";
}
};
int SI:: rate_of_interest =10; //Redeclaring and initializing Static variable

void main()
{
SI s1;
clrscr();
s1.get();
cout<<"\n The simple interest is @10% \n";
s1.put();
getch();
}

9220990566 CODINGBOSS YOUTUBE CHANNEL 5


OOP Chapter 2 Ali Karim Sir

2.2 Static member function:


Q. Explain the need of static member function with example.
Ans:
A static member 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 as follows:
class_name::function_name;
A static member of a class does not depend on any specific object of class. A static member function
can be called without existence of any of the class object.

//Static Data Member and Static Member Function


#include<iostream.h>
#include<conio.h>
class test
{
static int count; //static data member
public:
void setcount() //member function
{
count=count+1;
}
static void showcount() //static member function
{
cout<<"\n Static showcount():";
cout<<"\n count:"<<count;
}
};
int test :: count; //static data member redeclared outside class.
void main()
{
test t1,t2;
clrscr();
t1.setcount();
t2.setcount();
9220990566 CODINGBOSS YOUTUBE CHANNEL 6
OOP Chapter 2 Ali Karim Sir

test::showcount(); //Call to static member function.

getch();
}

Q Write program to define a class student having data members name and roll no. Accept and
display data for one object. (Class definition - 2 Marks, creating object t - 1 Mark, Function call -
1 Mark)
Ans:
#include<iostream.h>
#include<conio.h>
class student
{
private:
introll_no;
char name[20];
public :
void get()
{
cout<<"\nenterrollno& name";
cin>>roll_no>>name;
}

void put()
{
cout<<"\nroll_no\t" <<roll_no;
cout<<"\nname\t"<<name;
}
};
void main()
{
student s1;
s1.get();
s1.put();
getch();
}

2.2 Friend Function:


Q Define friend function. Write syntax of declaring it. (Definition - 2 Marks; Syntax - 2 Marks)
Ans:
Friend function: -
➢ The private members of a class cannot be accessed from outside the class but in some situations
two classes may need access of each other’s private data.

9220990566 CODINGBOSS YOUTUBE CHANNEL 7


OOP Chapter 2 Ali Karim Sir
➢ So a common function can be declared which can be made friend of more than one class to access
the private data of more than one class. The common function is made friendly with all those
classes whose private data need to be shared in that function.
➢ This common function is called as friend function. Friend function is not in the scope of the class
in which it is declared. It is called without any object.
➢ The class members are accessed with the object name and dot membership operator inside the
friend function. It accepts objects as arguments.
➢ It is not affected by the access control keywords (public, private and protected.)

Syntax:- friend return_type function_type(parameter1,parameter2,…,parameter n);

Syntax for calling friend function: - function_name(parameter1,parameter2,,parameter n);

Q. Explain the concept of friend function. (Explanation- 2 Marks; Syntax/ program- 2 Marks)
Ans:

➢ Friend functions Private and protected members of a class cannot be accessed from outside the same
class in which they are declared. However, this rule does not affect friends.
➢ A function that is not a member of a class but has access to the class ‘s private and protected members.
They are normal external functions that are given special access privileges.
➢ Friend function is declared by the class that is granting access. The friend declaration can be placed
anywhere in the class declaration.
➢ It is not affected by the access control keywords (public, private and protected.)

#include <iostream.h>
#include<conio.h>
class myclass
{
int num;
public:
myclass(int x)
{
num = x;
}
friend int isneg(myclass ob); //friend function declaration
};
int isneg(myclass ob) //friend function defination
{
return (ob.num< 0) ? 1 : 0;
}

void main()
{
myclass a(-1), b(2);
cout<<isneg(a) << ' ' <<isneg(b);
cout<<endl;
getch();
}

9220990566 CODINGBOSS YOUTUBE CHANNEL 8


OOP Chapter 2 Ali Karim Sir

Q. Write any two rules to define friend function. (Any two rules, Each rule – 1 Mark)
Ans:
Rules to define friend function:
1. It is not in the scope of the class to which it has been declared as friend.
2. As it is not in the scope of the class, it cannot be called using the object of that class.
3. It can be invoked like a normal function without the help of any object.
4. It cannot access the member names directly and has to use an object name and dot membership operator with
each member name.
5. It can be declared either in the public or the private part of a class without affecting its meaning.
6. It has the objects as arguments.

Q. Write a program to declare class ‘complex’ with data members x and y. Write member function to read
and print data members. Read x and y for two objects and add these two objects into third object using
friend function. (Class definition with read and print functions 4M, friend function definition 2M, main
function definition 2M)
Ans:
#include<iostream.h>
#include<conio.h>
class complex
{
intx,y;
public:
void read()
{
cout<<"Enter values for x and y:";
cin>>x>>y;
}
void print()
{
cout<<"x="<<x<<"y="<<y;
}
friend complex add(complex,complex);
};
complex add(complex a, complex b)
{
complex d;
d.x=a.x + b.x;
d.y=a.y + b.y;
return(d);
}
void main()
{
complex c1,c2,c;

9220990566 CODINGBOSS YOUTUBE CHANNEL 9


OOP Chapter 2 Ali Karim Sir
clrscr();
c1.read();
c2.read();
c=add(c1,c2);
c.print();
getch();
}

2.3 Array of Objects:


Q Write a program to declare a class staff having data members as name and post. Accept and display data
for five staff members. (Using array of object) (Class definition - 2 Marks, Creation and working of array -
2 Marks)
Ans:
#include<iostream.h>
#include<conio.h>
class staff
{
private:
char name[10],
post[10];
public:
void get()
{
cout<<"\n Enter staff name: ";
cin>>name;
cout<<"Enter staff post: ";
cin>>post;
}
void put()
{
cout<<"\n Name of staff: "<<name<<endl;
cout<<"Name of post: "<<post;
}
};
void main()
{
staff s[3]; //Array of Objects
int i;
clrscr();
cout<<"***Enter data in Array of Objects***";
for(i=0;i<3;i++)
{
s[i].get();
}
cout<<"***Output of Array of Objects***";

9220990566 CODINGBOSS YOUTUBE CHANNEL 10


OOP Chapter 2 Ali Karim Sir
for(i=0;i<3;i++)
{
s[i].put();
}
getch();
}

Output:

Q Write a program to declare class ‘staff’ having data members as name and post. Accept this data for 5
staffs and display name of staff who are HOD. (Declaring class with proper functions and data members - 3
Marks, creating ten objects – 1,Mark, accepting values - 1 Mark, displaying requiring data - 3 Marks)
Ans:
#include<iostream.h>
#include<conio.h>
#include<string.h>
class staff
{
char name[20],post[5];
public:
void accept()
{
cout<<"\nEnter Name:";
cin>>name;
cout<<"Enter Post:";
cin>>post;
}
void display()
{
if(strcmp(post,"HOD")==0)
{
cout<<"\nHOD: "<<name;
}
}
};
void main()
{

9220990566 CODINGBOSS YOUTUBE CHANNEL 11


OOP Chapter 2 Ali Karim Sir
staff s[3]; //Array of Objects
int i;
clrscr();
for(i=0;i<3;i++)
{
s[i].accept();
}

cout<<"\nStaff who are only HOD";


for(i=0;i<3;i++)
{
s[i].display();
}
getch();
}
Output:

Q Write a program to create a class “student” having data member as name. roll no. and percentage to
read and display details for 10 students. (Declaration of class with proper members-2Marks, creating array
of object and calling functions- 2Marks)
Ans:
#include<iosream.h>
class student
{
char name[10];
int rollno;
float percentage;
public:
void getdata()
{
cin>>name>>rollno>>percentage;
9220990566 CODINGBOSS YOUTUBE CHANNEL 12
OOP Chapter 2 Ali Karim Sir
}
void putdata()
{
cout<<name<<rollno<<percentage;
}
};

void main()
{
student s[10];
int i;
for(i=0;i<10;i++)
s[i].getdata();
for(i=0;i<10;i++)
s[i].putdata();
}

Q Write a program to define a structure ‘Tender’ having data members tender-no., cost and company-
name. Accept & display this data two variable of this structure. (Structure Declaration: 2 Marks, Accept
data for 2 variables: 1 Mark, Display data for 2 variables: 1 Mark)
Ans:
# include <conio.h>
#include<iostream.h>
struct tender
{
int tender_no;
float cost;
char company_name[20];
} t1,t2;

void main()
{
clrscr();
cout <<"Enter values for tender_number, cost and company for first tender";
cin>>t1.tender_no>>t1.cost>>t1.company_name;
cout <<"Enter values for tender_no,cost and company for second tender";
cin>>t2.tender_no>>t2.cost>>t2.company_name;
cout<<"\n Details of tender1 are:";
cout<<"\n tender no="<<t1.tender_no;
cout<<"\n tender cost="<<t1.cost;
cout<<”company name="<<t1.company_name;
cout<<"\n Details of tender2 are:";
cout<<"\n tender no="<<t2.tender_no;
cout<<"\n tender cost="<<t2.cost;
cout<<"\n company name="<<t2.company_name;
getch();
}

9220990566 CODINGBOSS YOUTUBE CHANNEL 13


OOP Chapter 2 Ali Karim Sir
Q Write a program to declare a class ‘Journal’ having data members as journal-name, price & no-of-pages.
Accept this data for two objects & display the name of journal having greater price.
(Class Declaration - 1 Mark, Creating two objects – 1 Mark, Accept and display data - 2 Marks)
Ans:
#include<conio.h>
#include<iostream.h>
class Journal
{
public:
char journal_name[20];
int no_of_pages;
float price;
void get()
{
cout<<"\n Enter value of journal name and no. of pages and price";
cin>>journal_name>>no_of_pages>>price;
}
void put()
{ cout<<"\n Journal Name="<<journal_name;
cout<<"\n No. of pages="<<no_of_pages;
cout<<"\n Price="<<price;
}

void main()
{
Journal J1,J2;
J1.get();
J2.get();
cout<<"\n details of journal having greater price";
if(J1.price > J2.price)
J1.put();
else
J2.put();
getch();
}

9220990566 CODINGBOSS YOUTUBE CHANNEL 14


OOP Chapter 2 Ali Karim Sir

Q Write a program to declare a class ‘staff’ having data member as name & department. Accept this data
for 10 staffs & display names of staff that are in cm department. (Declaring class with proper functions and
data members - 3 Marks, creating ten objects - 1 Mark, accepting values- 1 Mark, displaying requiring data -
3 Marks)
Ans:

#include<iostream.h>
#include<conio.h>
#include<string.h>
class staff
{
char name[20],
department[5];
public:
void accept()
{
cout<<"\nEnter Name and Department";
cin>>name>>department;
}
void display()
{
if(strcmp(department,"cm")==0)
{
cout<<"\nStaff "<<name<<" works in cm department";
}
}
};

void main()
{
staff s[10]; int i;
clrscr();
for(i=0;i<10;i++)
{ s[i].accept(); }
for(i=0;i<10;i++)
{ s[i].display(); }
getch();
}

2.3 Object as function arguments:


Q. Explain with example object as member function argument. (Any one method of explanation - 2M,
Example/program – 2M)
Ans.
An object may be used as function arguments in two methods:-
i) A copy of the entire object is passed to the function.
ii) Only the address of the object is transferred to the function.

9220990566 CODINGBOSS YOUTUBE CHANNEL 15


OOP Chapter 2 Ali Karim Sir
1) Pass-by-value
Since a copy of the object is passed to the function, any changes made to the object inside the function do not
affect the object used to call the function.
2) Pass-by-reference
When an address of the object is passed the called function works directly on the actual object used in the call.
This means that any changes made to the object inside the function will reflect in the actual object.
Example:
Following program illustrates the use of object as function arguments. It performs the addition of time in the hour
& minute format.
# include<iostream.h>
class time
{
int hours;
int minutes;
public:
void gettime(int h, int m)
{
hours = h;
minutes = m;
}
void puttime(void)
{
cout<< hours << "hours and: ";
cout<< minutes << " minutes " << "\n";
}
void sum (time, time);
};
void time :: sum (time t1, time t2)
{
minutes =t1.minutes + t2.minutes ;
hours = minutes / 60;
minutes = minutes%60;
hours = t1.hours + t2.hours;
}
void main()
{
time T1, T2, T3;
T1.gettime(2, 30);
T2.gettime(3, 45);
T3.sum(T1, T2);
cout<< " T1 = ";
T1.puttime();
cout<< " T2 = ";
T2.puttime();
cout<< " T3= ";
T3.puttime();
}
An object can also be passed as argument to a non-member function but, such functions can have access to the
public member function only through the object passed as arguments to it.
Example:
#include <iostream.h>
#include<conio.h>
9220990566 CODINGBOSS YOUTUBE CHANNEL 16
OOP Chapter 2 Ali Karim Sir
class rational
{
private:
int num;
int dnum;
public:
void get()
{
cout<<"\nEnter numerator:";
cin>>num;
cout<<"Enter denominator:";
cin>>dnum;
}
void print()
{
cout<<num<<"/"<<dnum<<endl;
}
void multi(rational r1,rational r2) // receiving object as argument
{
num=r1.num*r2.num;
dnum=r1.dnum*r2.dnum;
}
};
void main()
{
rational r1,r2,r3;
cout<<"Enter value in first obj r1:";
r1.get();
cout<<"Enter value in second obj r2:";
r2.get();
r3.multi(r1,r2); // sending object as an argument
cout<<"Result of obj r3:";
r3.print();
getch();
}
Output:

9220990566 CODINGBOSS YOUTUBE CHANNEL 17

You might also like