Object Oriented Programming with C++
Classes and objects
PART II
Answer to all the questions (2 Marks):
1. What are called members?
Answer: Data member and member functions are called class members
2. Differentiate structure and class though both are user defined data type.
Answer: The only difference between structure and class is the members
of structure are by default public where as it is private in class.
3. What is the difference between the class and object in terms of oop?
Class
• Class is a data type.
• It generates objects.
• Does not occupy memory location.
• It cannot be manipulated.
Object
• Object is an instance of class.
• It gives life to class.
• It occupies memory location.
• It can be manipulated.
4. Why it is considered as a good practice to define a constructor though compiler can automatically generate a constructor ?
Answer:
(i) To allocate memory space to the object and
(ii) To initialize the data member of the class object
5. Write down the importance of destructor.
Answer: The purpose of the destructor is to free the resources that the
object may have acquired during its lifetime. A destructor function removes the
memory of an object which was allocated by the constructor at the time of
creating a object.
PART III
Answer to all the questions(3 Marks):
1. Rewrite the following program after removing the syntax errors if any and underline the errors:
#include<iostream>
#include<stdio.h>
classmystud
{ intstudid =1001; char name[20];
public
mystud( )
{ }
void register ( ) {cin>>stdid;gets(name);
}
void display ( )
{ cout<<studid<<”: “<<name<<endl;}
}
int main( )
{ mystud MS; register.MS( ); MS.display( );
}
Answer:
#include<iostream>
#include<stdio.h>
class mystud
{
int studid;
char name[20];
public:
mystud()
studid - 0;
name = Null;
{
void register ( )
{
cin>>studid;
gets(name);
}
void display()
{
cout<<studid<<": "<<name<<endl;
}
int main ()
{
mystud MS;
MS.register( );
MS.display( );
return 0;
}
2. Write with example how will you dynamically initialize objects?
Answer: When the initial values are provided during runtime then it is
called dynamic initialization.
To illustrate dynamic initialization!
#include<iostream>
using namespace std;
class X
{
int n;
float avg;
public;
X(int p, float q)
{
n=p;
avg=q:
}
void disp()
{
Cout<<"\n Roll number:-"<<n;
cout<<"\nAverage:-"<<avg;
}
};
int main( )
{
int a; float b;
cout<<"\n Enter the Roll number";
cin>>a;
cout<<"\nEnter the Average";
cin>>b;
X x(a,b); \\dynamic
initialization
x.disp( );
return 0;
}
Output:
Enter the Roll Number 1201
Enter the Average 98.6
Roll number:- 1201
Average:- 98.6
3. What are advantages of declaring constructors and destructor under public accessability?
Answer: The advantages of declaring constructors and destructor under
public accessibility is that its object can be created in any function.
4. Given the following C++ code, answer the questions (i) & (ii).
class TestMeOut
{
public:
~TestMeOut() //Function 1
{cout<<“Leaving the examination hall”<<endl;}
TestMeOut() //Function 2 {cout<<“Appearing for examination”<<endl;}
void MyWork() //Function 3 {cout<<“Attempting Questions//<<endl;}
};
(i) In Object Oriented Programming, what is Function 1 referred as and when doesit get invoked / called ?
(ii) In Object Oriented Programming, what is Function 2 referred as and when doesit get invoked / called ?
Answer: (i) Destructor, when an instance of a class goes out of scope
the destructor gets invoked / called.
(ii) Constructor, when an instance of a class comes into scope
the constructor gets invoked/ called.
5. Write the output of the following C++ program code :
#include<iostream>
using namespace std;
class Calci
{
char Grade;
int Bonus;
public:
Calci() {Grade='E'; Bonus=0;} //ascii value of A=65
void Down(int G)
{
Grade-=G;
}
void Up(int G)
{
Grade+=G;
Bonus++;
}
void Show()
{
cout<<Grade<<"#"<<Bonus<<endl;
}
};
int main()
{
Calci c;
c.Down(3);
c.Show();
c.Up(7);
c.Show();
c.Down(2);
c.Show();
return 0;
}
Answer:
B#()
I#1
G#1
PART IV
Answer to all the questions (5 Marks):
1. Explain nested class with example.
Answer:
Nested class : When one class become the member of another class then it is
called Nested class and the relationship is called containership.
Classes can be
nested in two ways.
1. By defining a class within another class
2. By declaring an object of a class as a member to another
class.
Defining a class
with in another : When a class is declared with in
another class, the inner class is called as Nested class (ie the inner class)
and the outer class is known as Enclosing class. Nested class can be defined in
private as well as in the public section of the Enclosing class.
C++ program to illustrate the nested class
#include<iostream>
using namespace std;
class enclose
{
private:
int x;
class nest
{
private :
int y;
public:
int z;
void prn()
{
y=3;z=2;
cout<<"\n The product
of'<<y<<'*'<<z<<"= "<<y*z<<"\n";
}
}; //inner class
definition over
nest n1;
public:
nest n2;
void square( )
{
n2.prn(); //inner
class member function is called by its object
x=2;
n2.z=4;
cout<<"\n The product of "
<<n2.z<<'*'<<n2.z<<"=
"<<n2.z*n2.z<<"\n";
cout<<"\n The product of "
<<x<<'*'<<x<<"="<<x*x;
}
}; //outer class
definition over
int main()
{
enclose e;.
e.square(); //outer class member function is called
}
Output:
The product of 3*2=6
The product of 4*4=16
The product of 2*2=4
In the above program the inner class nest is defined inside the
outer class enclose, nest is accessed by enclose by creating an object of nest.
2. Mention the differences between constructor and destructor
1. Purpose :
Constructor: It allocates the memory to an
object.
Destructor: It deallocates the
memory of an object.
2. Declaration
Constructor: Class-name (argument if any) {};
Destructor: ~ class - name (no
arguments) {};
3. Arguments
Constructor: constructor accepts argument
Destructor: Destructor does not
accepts any argument.
4. Numbers
Constructor: There can be multiple constructor in
the class.
Destructor: But there is always
a single destructor in the class.
5. over loading
Constructor: Constructors can be overloading
Destructor: Destructor cannot
be overloaded.
3. Define a class RESORT with the following description in C++ :
Private members:
Rno // Data member to store room number
Name //Data member to store user name
Charges //Data member to store per day charge
Days //Data member to store the number of days
Compute ( ) // A function to calculate total amount as Days * Charges and if the
//total amount exceeds 11000 then total amount is 1.02 * Days *Charges
Public member:
getinfo( ) // Function to Read the information like name , room no, charges and days
dispinfo ( ) // Function to display all entered details and total amount calculated //using COMPUTE function
Answer:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class RESORT
{
int tno, days;
char name[20];
float charges;
float compute();
public :
void getinfo();
void dispinfo() ;
};
void RESORT:: get.info()
{
Cout<<"Room Number :"<<endl;
cin>>rno;
cout<<"Name"<<endl;
gets(name);
cout<<"charges"<<endl;
cin>>charges;
cout<<"Number of Days"<<endl;
cin>>days;
}
void RESORT:: dispinfo()
{
Cout<<endl<<”Details follow"<<endl;
Cout<<"Room Number: "<<rno<<endl;
Cout<<"Name
:"<<name<<endl;
Cout<<"Charges : "<<charges<<endl;
Cout<<"Number of days:"<<days<<endl;
cout<<"Amout :"<<compute()<<endl;
}
float RESORT:: Compute()
{
float amount = charges * days;
if(amount > 11000)
amount=
1.02*days*charges;
return amount;
}
int main()
clrscr();
{
RESORT rl;
rl.getinfo();
rl.disprinfo();
getch;
return 0;
}
4. Write the output of the following
#include<iostream>
#include<stdio.h>
using namespace std;
class sub
{
int day, subno;
public :
sub(int,int); // prototype
void printsub()
{ cout<<" subject number : "<<subno;
cout<<" Days : " <<day;
}
};
sub::sub(int d=150,int sn=12)
{ cout<<endl<<"Constructing the object "<<endl;
day=d;
sub no=sn;
}
class stud
{
int rno;
float marks;
public:
stud( )
{ cout<<"Constructing the object of students "<<endl; rno=0;
marks=0.0;
}
void getval()
{
cout<<"Enter the roll number and the marks secured ";
cin>>rno>>marks;
}
void printdet()
{ cout<<"Roll no : "<<rno<<"Marks : "<<marks<<endl;
}
};
class addmission {
sub obj;
stud objone;
float fees;
public :
add mission ( )
{ cout<< "Constructing the object of admission "<<endl; fees=0.0;
}
void printdet( )
{ objone.printdet(); obj.printsub( );
cout<<"fees : "<<fees<<endl ;
}
};
int main()
{system("cls");
addmission adm;
cout<<endl<< "Back in main ( )";
return 0; }
Answer:
Constructing the object
Constructing the object of students
Constructing the object of admission
Back in main ()
5. Write the output of the following
#include<iostream>
#include<stdio.h>
using namespace std;
class P
{ public:
P ( )
{ cout<< "\nConstructor of class P "; }
~P()
{ cout<< "\nDestructor of class P "; }
};
class Q
{ public:
Q( )
{ cout<<"\nConstructor of class Q "; }
~Q()
{ cout<< "\nDestructor of class Q "; } };
class R
{ P obj1, obj2;
Q obj3;
public:
R ( )
{ cout<< "\nConstructor of class R ";}
~R()
{ cout<< "\nDestructor of class R ";} };
int main ( )
{
Ro R;
Q oq;
P op;
return 0;
}
Answer:
Constructor of class P
Constructor of class Q
Constructor of class R
Destructor of class R
Destructor of class Q
Destructor of class P
EVALUATE YOURSELF
1. Define a class in general and
in C++’s context.
Answer: (i) In general, classes are used to represent read world
entities that have both properties and operations.
(ii) In C++, class is a way to bind the data and its associated
functions together.
2. What is the purpose of a class
specifier?
Answer: Class specifier intimates the compiler that it is a class
definition.
3. Compare a structure and a
class in C++ context.
Answer: (i) A class in C++ can be defined as a collection of related
variables and functions encapsulated in a single structure.
(ii) A structure in C++ can be referred to an user defined data
type possessing its own operations.
4. Compare private and public
access specifier.
Answer: (i) A private member cannot be accessed from outside the class.
(ii) A public member is accessible from anywhere outside the
class.
5. What is non-inline member
function? Write its syntax.
Answer: When member function defined outside the class called a
non-inline member function.
Syntax :
return_type class_name : : function_name(parameter list)
{
function definition
}
Hands on practice:
1. Define a class Employee with the following specification
private members of class Employee
empno- integer
ename – 20 characters
basic – float
netpay, hra, da, - float
calculate () – A function to find the basic+hra+da with float return type
public member functions of class employee
havedata() – A function to accept values for empno, ename, basic, hra,
da and call calculate() to compute netpay
dispdata() – A function to display all the data members on the screen
Answer:
#include<iostream.h>
#include<string.h>
class Employee
{
int empno;
char ename[20];
float basic,netpay,hra,da;
float calculate();
public:
void havedata ( )
{
Cout<<"Enter Employee Number"<<endl;
cin<<empno;
cout<<"Enter Employee Name"<<endl;
gets(ename);
cout<<"Enter Basic Pay"<<endl;
cin>>basic;
cout<<"Enter HRA"<<endl;
cin>>hra;
cout<<"Enter DA"<<endl;
cin>>da;
calculate ();
}
float calculate ()
{
netpay = basic + hra + da;
return netpay;
}
void dispdata( )
{
Cout<<"Employee Number :"<<empno<<endl;
Cout<<"Employee Name
:"<<ename<<endl;
cout<<"BASIC PAY :"<<basic<<endl;
cout<<"HRA :"<<ha<<endl;
cout<<"DA:"<<da<<endl;
cout<<"Netpay :"<<calculate<<endl;
}
};
int main ()
{
Emplyee e;
e.havedata ();
e.calculate ();
e.dispdata ();
return 0;
}
2. Define a class MATH with the following specifications
private members
num1, num2, result – float
init() function to initialize num1, num2 and result to zero
protected members
add() function to add num1 and num2 and store the sum in result
diff() function to subtract num1 from num2 and store the difference in the result
public members
getdata() function to accept values for num1 and num2
menu() function to display menu
1. Add…
2. Subtract…
invoke add() when choice is 1 and invoke prod when choice is 2 and also display the result.
Answer:
class MATH
{
float num 1, num2, result;
void init()
{
numl = 0.0;
num2 = 0.0;
result = 0.0;
}
protected :
void add( )
{
result = numl + num 2;
cout<<"Result:"<<result;
}
void diff()
{
result = numl − num 2;
cout<<"Result:"<<result;
}
pulic;
void getdata()
{
Cout<<"Enter first value”<<endl;
cin>>numl;
cout<<"Enter Second value"<<endl;
cin>>num2;
}
};
int main ( )
{
MATH m;
int ch;
cout<<"l.Add..."<<endl;
cout<<"2. Subtract... "<<endl;
cin>>ch;
swith(ch)
{
case 1:
cout<<"Addition:<<endl;
m.getdata;
m.add( );
break;
case 2:
cout<<"Subtraction:<<endl;
m.getdata;
m.diff( );
break;
default:
cout<<"Invalid choice"<<endl;
}
return 0;
}
3. Create a class called Item with the following specifications
private members
code, quantity - Integer data type
price - Float data type
getdata()-function to accept values for all data members with no return public members
taxt – float
dispdata() member function to display code,quantity,price and tax .The tax is calculated as if the quantity is more than 100 tax is 2500 otherwise 1000.
Answer:
#include<iostream.h>
class Item
{
int code, quantity;
float price;
void getdata ( );
public :
float taxt;
void dispdata();
};
void Item :: getdata()
{
Cout<<"Enter code"<<endl;
Cin>>code;
Cout<<"Enter Quantity"<<endl;
cin>>Quantity;
cout<<"Enter price"<<endl;
cin>>price;
}
void item :: dispdata()
{
Cout<<"CODE"<<code<<endl;
Cout<<"Quantity”<<auantity<<endl;
Cout<<"PRICE"<<price<<endl;
text = Quantity> 100 ? 2500 : 1000;
cout<<"TAX : "<<text;
}
int main ()
{
Item t;
t.getdata();
t.dispdata();
return 0;
}
4. Write the definition of a class FRAME in C++ with following description
Private members
FrameID - Integer data type
Height, Width, Amount - Float data type
SetAmount( ) -Member function to calculate and assign amount as 10*Height*Width
Public members
GetDetail() Afunction to allow user to entervalues of
FrameID, Height, Width. This function should also call SetAmount() to calculate the amount.
ShowDetail() A function to display the values of all data members.
Answer:
#include<iostream.h>
class FRAME
{
int framelD;
float Height, Width, Amount;
float setamount():
public:
void GetDetail();
void ShowDetail();
};
void FRAME :: GetDetail()
{
Cout<<"Enter FrameID"<<endl;
cin>>FrameID;
cout<<"Enter Height"<<endl;
cin>>Height;
cout<<"Enter Width"<<endl;
cin>>Width;
}
void FRAME :: ShowDetail()
{
Cout<<endl<<"Details"<<endl;
cout<<"FRAME ID"<<Frame ID<<endl;
cout<<"Height"<<Height<<endl;
cout<<"Width"<<Width<<endl;
cout<<"Amount"<<Amount<();
}
float FRAME :: setAmount()
{
amount = 10*Height*width;
return amount;
}
int main()
{
FRAME fl;
Fl.GetDetail();
Fl .ShowDetail();
return 0;
}
5. Define a class RESORT in C++ with the following description :
Private Members :
Rno //Data member to store Room No
RName //Data member t store customer name
Charges //Data member to store per day charges
Days //Data member to store number of days of stay
COMPUTE() //A function to calculate and return Amount as
//Days*Chagres and if the value of Days*Charges is more than 5000 then as 1.02*Days*Charges
Public Members :
Getinfo() //A function to enter the content Rno, Name, Charges //and Days
Displayinfo() //A function to display Rno, RName, Charges, Days and
//Amount (Amount to displayed by calling function COMPUTE( ))
Answer:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class RESORT
{
int tno, days;
char name[20];
float charges;
float compute();
public :
void getinfo( );
void dispinfo( );
void RESORT :: get.info( )
{
cout<<"Room Number :"<<endl;
cin>>rno;
cout<<"Name"<<endl;
gets(name);
cout<<"charges"<<endl;
cin>>charges;
cout<<"Number of Days"<<endl;
cin>>days;
}
void RESORT :: dispinfor()
{
Cout<<endl<<"Details follow"<<endl;
Cout<<" Room Number: "<<mo<<endl;
Cout<<"Name :"<<name<<endl;
Cout<<"Charges : "<<charges<<endl;
Cout<<"Number of days:"<<days<<endl;
Cout<<"Amout :"<<compute()<<endl;
}
float RESORT :: Compte()
{
float amount = charges * days;
if(amount > 11000)
amount=l .02*days*charges;
return amount;
}
int main()
ctrscrc();
{
RESORT rl;
rl .getinfo();
rl .disprinfo();
getch;
return 0;
}
6. struct pno
{
int pin;
float balance;
}
Create a BankAccount classwith the following specifications
Protected members
pno_obj //array of 10 elements
init(pin) // to accept the pin number and initialize it and initialize
//the balance amount is 0
public members
deposit(pin, amount):
Increment the account balance by accepting the amount and pin. Check the pin number for matching. If it matches increment the balance and display the balance else display an appropriate message
withdraw(self, pin, amount):
Decrement the account balance by accepting the amount and pin. Check the pin number for matching and balance is greater than 1000 and amount is less than the balance. If it matches withdraw the amount and display the balance else display an appropriate message
Answer:
#include<iostream.h>
#include<iomanip.h>
class Bank Account
{
int pinno [10];
float balance ;
protected ;
Bank Account ()
{
balance = 0.0;
}
public :
deposit (pin, amount);
withdraw(pin, amount);
void readpin( )
{
Cout<<"Enter pin nos" <<end1;
for (int i = 0; i<=9;i++)
cin>> pin[i];
}
};
Bank Account: deposit (pin, amount)
{
for(int i = 0; i<=9; i ++)
{
if(pinno[i] == pin)
balance = balance + amount;
}
Cout<<"Deposited Amount"<<balance;
}
Bank Account: Withdraw (pin, amount)
{
for(int i = 0 ; i<=9; i ++)
{
if ( (pinno[i] = = pin ) && (balance >1000) )
balance = balance − amount;
}
Cout<<"withdrawal amount<< balance;
}
};
int main ()
{
Bank Account BI;
B1. readpin( );
B1. deposit (1002, 10000);
B1.withdraw( 1002, 5000);
return 0 ;
}
7. Define a class Hotel in C++ with the following description :
Private Members :
Rno //Data member to store Room No
Name //Data member t store customer name
Charges //Data member to store per day charges
Days //Data member to store number of days of stay
Calculate() //A function to calculate and return Amount as Days*Chagres and if the value of Days*Charges is more than 12000 then as 1.2*Days*Charges
Public Members :
Hotel() //to initialize the class members
Getinfo() //A function to enter the content Rno, Name, Charges //and Days
Showinfo() //A function to display Rno, RName, Charges, Days and
//Amount (Amount to displayed by calling function
CALCULATE( ))
Answer:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class Hotel
{
int rno, days;
char Name[20];
float charges;
float calculate();
public:
Hotel()
{
rno = 0;
Name = Null;
charges = 0.0;
days = 0;
}
void getinfo();
void showinfo();
};
void Hotel:: getinfo()
{
Cout<<"Room Number:"<<endl;
cin<<rno;
cout<<"Name"<<endl;
gets(Name);
cout<<"Charges:"<<endl;
cin>>charges;
cout<<"Number of days:"<<endl;
cin>>days;
}
void Hotel :: showinfo()
{
Cout<<end<<"Hotel details as
follow"<<endl;
Cout<<"Room Number: "<<rno<<endl;
Cout<<"Name:"<<Name<<endl;
cout<<"Charges:"<<Charges<<endl;
cout<<"Number of days:"<<days<<endl;
cout<<"Amount:"<<calculate()<<endl;
}
float Hotel : Calculate()
{
float amount = charges * days;
if (amount > 12000)
amount = 1.2*days*charges;
return amount;
}
int main ()
{
clrscr()
Hotel Hl;
Hl.get_info();
Hl.showinfo();
getch;
return 0;
}
8. Define a class Exam in C++ with the following description :
Private Members :
Rollno - Integer data type
Cname - 25 characters
Mark - Integer data type
public :
Exam(int,char[],int ) //to initialize the object
~Exam( ) // display message “Result will be intimated shortly”
void Display( ) // to display all the details if t the mark is
//above 60 other wise display “Result Withheld”
Answer:
#include<iostream.h>
#include<stdio.h>
#include<string.h>
class Exam
{
int Rollno;
charCName[25];
int Mark;
public;
Exam(int, Char[], int);
~Exam;
void Display();
};
Exam:; Exam(int r, char CN[], int m)
{
Rollno = r;
strcpy(cname, cn);
Mark = m;
}
Exam ::~Exam()
{
Cout<<"Result will be intimated shortly"<<endl;
}
Exam :: Display()
{
if (Mark>=60)
cout<<"Roll No:"<<Rollno<<endl;
cout<<"Name:"<<name<<endl;
cout<<"Mark:"<<mark<<endl;
}
else
{
cout<"Result withheld"<<end1;
}
int main()
{
Exam E(11201, "ROHIT", 65);
E.display();
return 0;
}
9. Define a class Studentin C++ with the following specification :
Private Members :
A data member Rno(Registration Number) type long A data member Cname of type string
A data member Agg_marks (Aggregate Marks) of type float A data member Grade of type char
A member function setGrade () to find the grade as per the aggregate marks obtained by the student. Equivalent aggregate marks range and the respective grade as shown below.
Aggregate Marks : Grade
>=90 : A
Less than 90 and >=75 : B
Less than 75 and >=50 : C
Less than 50 : D
Public members:
A constructor to assign default values to data members:
A copy constructor to store the value in another object
Rno=0,Cname=”N.A”,Agg_marks=0.0
A function Getdata () to allow users to enter values for Rno.Cname, Agg_marks and call
functionsetGrade () to find the grade.
A function dispResult( ) to allow user to view the content of all the data members.
A destructor to display the message “END”
Answer:
#include<iostream.h>
#include<string.h>
class Student
{
long RNo;
char Cname[25];
float Agg_Marks;
char Grade;
char setGrade( );
Public :
Student();
Student(Student &s);
void Getdata();
void dispResult();
~Student();
};
Student:: Student()
{
Rno = 0;
Cname = Null;
Agg_marks = 0.0;
Grade =’ ’;
}
student: : (student & s)
{
Rno = s.Rno;
strcpy (cname, s.(Name); Agg- marks =s.Agg-marks
}
void student: Getdata()
{
Cout<<"Enter Roll Number"<<endl';
cin>>RNo;
Cout<<" Enter Name"<<endl';
cin>>(cname);
Cout<<"Enter Agg_marks"<<endl';
cin>>Agg_marks;
}
void student:: dispResult()
cout<<"Roll Number:"<<RNo<<endl;
cout<<"Name:"<<Cname<<endl;
cout<<"Aggregate
Marks:"<<Agg_marks<<endl;
cout<<"Grade:"<<setGrade<<endl;
}
void student:: setGrade()
{
if (Agg_marks>=90)
Grade = 'A';
else if (Agg_marks>=75 & Agg_marks<90)
Grade = 'B';
else if (Agg_marks>=50 & Agg_marks<75)
Grade = ’C’;
else
Grade = ’D’;
return Grade;
}
………………….
Student :: ~Student ()
int main() {
cout<<"END";
Student s1, s2(s1);
sl.Getdata()
sl.dispResult;
s2.dispResult;
}
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.