Professional Documents
Culture Documents
2.8 Create a class Person with data members: name, age and address. Create another class
Teacher with data members: qualification and department. Also create another class
Studentwith data members: programs and semester. Both classes are inherited from the
class Person. Every class has at least one constructor which uses base class constructor.
Create member function showdata() in each to display the information of the class
member. [2014 Spring]
#include<iostream>
using namespace std;
class Person
{
protected:
char name[20],address[20];
int age;
public:
Person()
{
}
showdata1()
{
cout<<"enter name,age,address"<<endl;
cin>>name>>age>>address;
cout<<"The details are:"<<endl;
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
cout<<"address:"<<address<<endl;
}
};
class Teacher:public Person
{
protected:
char qualification[20],department[20];
public:
Teacher()
{
}
showdata2()
{
cout<<"enter qualification and department"<<endl;
cin>>qualification>>department;
cout<<"The details are:"<<endl;
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
cout<<"address:"<<address<<endl;
cout<<"qualification:"<<qualification<<endl;
cout<<"department:"<<department<<endl;
}
};
class Student:public Person
{
protected:
char programs[20],semester[20];
public:
Student()
{
}
showdata3()
{
cout<<"enter programs and semester"<<endl;
cin>>programs>>semester;
cout<<"The details are:"<<endl;
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
cout<<"address:"<<address<<endl;
cout<<"programs:"<<programs<<endl;
cout<<"semester:"<<semester<<endl;
}
};
main()
{
Student s;
s.showdata1();
s.showdata3();
Teacher t;
t.showdata1();
t.showdata2();
}
3.8 A constructor is a special member function that automatically initializes the objects of
its class. support this statement with a program of all types of constructors. Also enlist the
characters of constructors. [2015 Spring]
Constructors are special class functions which performs initialization of every object. The
Compiler calls the Constructor whenever an object is created. Constructors initialize values to
object members after storage is allocated to the object. They are different from a normal member
function in following ways:
Constructor has same name as the class itself.
Constructor don’t have return type.
A constructor is automatically called when the object is created.
If we don’t specify a constructor, c++ compiler generates a default constructor for us
(expercts on parameter and has an empty body)
Following is the syntax of defining a constructor function in a class:
class A
{
public:
int x;
// constructor
A()
{
// object initialization
}
};
1. Default Constructor
Default constructor is the constructor which doesn't take any argument. It has no parameter.
Syntax:
// constructor Definition
For example:
class Cube
public:
int side;
Cube()
{
side = 15;
};
int main()
Cube c;
Output
15
2. Parametrized Constructor
These are the constructors with parameter. Using this Constructor you can provide different
values to data members of different objects, by passing the appropriate values as argument.
For example:
class Cube
public:
int side;
Cube(int x)
side=x;
};
int main()
Cube c1(10);
Cube c2(20);
Cube c3(30);
3. Copy Constructor
These are special type of Constructors which takes an object as argument, and is used to copy
values of data members of one object into other object.
For examples.
class Student
{
public:
int rollno;
string name;
// first constructor
Student(int x)
{
rollno = x;
name = "None";
}
// second constructor
Student(int x, string str)
{
rollno = x;
name = str;
}
};
int main()
{
// student A initialized with roll no 10 and name None
Student A(10);
Characteristics of Constructors
• They cannot be inherited but a derived class can call the base class constructor
• A constructor can be used explicitly to create new object of its class type.
4.8 Discuss the context where it becomes important to make the base class virtual. Also
include an appropriate example. [2014 Fall]
Grand Parent
Parent 1 Parent 2
Child
Let us consider an example of hybrid inheritance. From the figure, the child class has two direct
base classes: parent1 and parent 2 which themselves have common class grandparent. The child
inherits the characteristics of grandparents via two separate paths.
In the diagram, all the public and protected member of grandparent are inherited in the child
twice: first via parent 1 and second via parent 2. This means child would have duplicate set of
members inherited from grandparent, thus introduces duplication and should be avoided. The
duplication of inherited members due to their multipath can be avoided by making common base
class as virtual class such class is called virtual base class. This helps us to inherit directly as
shown in the broken line.
General syntax is:
Class Grandparent
{
………………………………..
……………………….
};
Class parent1: virtual public Grandparent
{
…………..
……….
};
Class parent2: virtual public grandparent
{
………….
…………..
};
Class child: public parent1, public parent2
{
………..//only one copy of grandparent will be inherited
…….
};
Main()
{
…………..
…………
}
Hence virtual base classes are used in virtual inheritance in a way of preventing multiple
“instances” of a given class appearing in an inheritance when using multiple inheritances.
A virtual function allows derived classes to replace the implementation provided by the base
class. The compiler makes sure the replacement is always called whenever the object in question
is actually of the derived class, even if the object is accessed by a base pointer rather than a
derived pointer.
Sample program
#include<iostream>
using namespace std;
class student
{
protected:
int roll;
public :
void get_roll()
{
cout<<"enter roll no:"<<endl;
cin>>roll;
}
void show_roll()
{
cout<<"rollno is:"<<roll<<endl;
}
};
class exam: virtual public student
{
protected:
int m1,m2;
public:
void get_mark()
{
cout<<"enter mark1 and mark2"<<endl;
cin>>m1>>m2;
}
void show_mark()
{
cout<<"mark1="<<m1<<endl;
cout<<"mark2="<<m2<<endl;
}
};
class sports: virtual public student
{
protected:
int sc;
public:
void get_score()
{
cout<<"enter score in sports:"<<endl;
cin>>sc;
}
void show_score()
{
cout<<"score="<<sc<<endl;
}
};
class result: public exam, public sports
{
public:
int tot;
void show_total()
{
tot=m1+m2+sc;
cout<<"total="<<tot<<endl;
}
};
main()
{
result r;
r.get_roll();
r.get_mark();
r.get_score();
r.show_roll();
r.show_mark();
r.show_score();
r.show_total();
}
5.8 What is the benefit of overloading an operator? Design a SoccerPlayer class that
includes three integer fields: a player’s jersey number, number of goals, number of assists
and necessary constructors to initialize the data members. Overload the > operator
(greater than). One player is considered greater than another if the sum of goals pls assists
is greater than that of the others. Create and array of 11 soccer players, then use the
overload > operator to find the player who has the greatest total of goals plus assists. [2015
Fall]
Operator overloading is the use of operator for different purpose in different datatypes which is
done by using keyword operator. The benefit of overloading an operator are given below:-
Operator overloading enable programmers to use notation closer to the target domain.
Operator overloading provides similar syntactic support of built in types to user defined
type.
Operator overloading makes the program easier to understand.
It increases the readability of the program for eg: it is easy to read C3=C1+C2 rather than
C3=C1sumC2; where C1 and C2 are object.
The type conversion operators can be over ridden to convert a user defined to a built in
type or to other user defined data type.
Operator overloading helps in extending the application of an operator.
#include<conio.h>
#include<iostream>
using namespace std:
Class Soccerplayer
{
Friend std:: ostream & operator<<(std::ostream&, const soccerplayer&);
Friend istream & operator >> (istream &, Soccerplayer&);
Private:
int jerseynum;
int numgoals;
int numassists;
Public:
Soccerplayer(int, int, int)
int score;
int operator > (Soccerplayer&);
void Displaystar();
};
Soccerplayer:: Soccerplayer (int jersey = 0, int goal=0 int assist=0);
{
jerseynum= jersey;
numgoals= goal;
numassists=assist;
}
void soccerplayer::Displaystar();
{
cout<<"Player name"<<jerseynum<<endl;
cout<<"Goals scored"<<numgoals<<endl;
cout<<"ASsists made"<<numassist<,endl;
}
std::ostream&operator<<(std::ostream & player, const soccerplayer & aplayer)
{
player<<" jersey#"<<aplayer.jerseynum<<"Number of
goals"<<aplayer.numgoals<<"Number of ASsists"<<aplayer.numassists;
return player;
}
std::istream & operator>>(std::istream & inplayer, soccerplayer & a player )
{
cout<<"Please enter jersey number:";
inplayer>>aplayer.jerseynum;
cout<<"Please enter no of goals";
inplayer>>aplayer.numgoals;
cout<<"please enter thenumber of assists ";
inplayer>>aplayer.numassists;
aplayer.score=(aplayer.numgoals)+(aplayer.numassists);
return inplayer;
}
intsoccerplayer;;operator>(soccerplayer& aplayer)
{
int total=0;
if (score>aplayer.score)
total=1;
return total;
}
int main()
{
const int sz=11;
intx;
soccerplayer aplayer[sz];
For (x=0;x<sz;++x)
cin>>aplayer[x];
{
double.max=aplayer[s].score;
for(int i=1:i<sz:++i)
{
if (aplayer[i]>aplayer[x])
{
max=aplayer[i].score;
}
}
cout<<max<<endl;
cout<<aolayer[s];
}
getch();
return0;
}
6.8 What is exception? Write the syntax for exception handling in C++. WAP that catches
multiple exceptions. [2016 Spring]
An exception is a problem that arises during the execution of a program. A C++ exception is a
response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.
throw − A program throws an exception when a problem shows up. This is done using
a throw keyword.
catch − A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception.
try − A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.
The syntax for exception handling in C++
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
The program that catches multiple exceptions:
#include<iostream>
#include<conio.h>
using namespace std;
main()
{
int id, num[5]={10,20,30,40,50};
int a,b,c;
cout<<"Enter two numbers"<<endl;
cin>>a>>b;
cout<<"Enter the array index to display the data"<<endl;
cin>>id;
try
{
if(b==0)
throw"Divide by zero not possible";
else if (id>4)
throw"Array index out of range";
else
{
c=a/b;
cout<<"Result="<<endl;
cout<<num[id]<<endl;
}
}