Unit 2 - Mahalakshmi Engineering College

advertisement
QUESTION BANK
DEPARTMENT:EEE
SEMESTER: V
SUBJECT CODE / Name:CS2311 – OBJECT ORIENTED PROGRAMMING
UNIT – II
PART - A (2 Marks)
1. Why cant friend function be used to overload assignment operator? (AUC DEC
2012)
Assignment(=) operator is a special operator that will be provided by the constructor
to the class when programmer has not provided(overloaded) as member of the
class.(like
copy
constructor).
When programmer is overloading = operator using friend function, two = operations
will exists:
1) compiler is providing = operator
2) programmer is providing (overloading) = operator by friend function.
Then simply ambiguity will be created and compiler will gives error. It‟s a compilation
error.
2. What is a virtual class? Why is it used in C++? (AUC DEC 2012, 2011)
A base class that is qualified as virtual in the inheritance definition. In case of multiple
inheritance, if the base class is not virtual the derived class will inherit more than one
copy of members of the base class. For a virtual base class only one copy of
members will be inherited regardless of number of inheritance paths between base
class
and
derived
class.
Eg: Processing of students‟ results. Assume that class sports derive the roll
number from class student. Class test is derived from class Student. Class result is
derived from class Test and sports as a virtual base class
3. List the operators that cannot be overloaded.(AUC MAY 2012)
Class member access operator (. , .*)
Scope resolution operator (::)
Size operator ( sizeof )
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
1
Conditional operator (?:)
4. What are pure virtual functions? Where are they used? (AUC MAY 2012)
A pure virtual function is a function declared in a base class that has no
definition relative to the base class. In such cases, the compiler requires each
derived class to either define the function or redeclare it as a pure virtual function. A
class containing pure virtual functions cannot be used to declare any object of its
own. It is also known as “donothing” function.
The “do-nothing” function is defined as follows: virtual void display ( ) =0;
5. What is a friend function? (AUC DEC 2011)
A function that has access to the private member of the class but is not itself a
member of the class is called friend functions.
The general form is
friend data_type function_name( );
Friend function is preceded by the keyword „friend‟.
6. What is a virtual base class? (AUC DEC 2011)
A base class that is qualified as virtual in the inheritance definition. In case of multiple
inheritance, if the base class is not virtual the derived class will inherit more than one
copy of members of the base class. For a virtual base class only one copy of
members will be inherited regardless of number of inheritance paths between base
class and derived class.
Eg: Processing of students‟ results. Assume that class sports derive the roll
number from class student. Class test is derived from class Student. Class result is
derived from class Test and sports as a virtual base class
7. What is encapsulation? Do friend functions violate encapsulation? (AUC DEC
2010)
Wrapping up of data and function within the structure is called as encapsulation.
Friend functions violate encapsulation as they can get access to members of class.
8. How are virtual functions declared in C++? (AUC DEC 2010)
A function qualified by the „virtual‟ keyword is called virtual function. When a virtual
function is called through a pointer, class of the object pointed to determine which
function definition will be used.
9. What is the main purpose of a template in C++? Give an example.(May
2006,May 2012)
If a set of functions or classes have the same functionality for different data types, they
becomes good candidates for being written as Templates. C++ Class Templates are suited
can be container classes. Very famous examples for these container classes will be the STL
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
2
classes like vector, list etc. Declaration of C++ class template should start with the keyword
template
//Sample code snippet for C++ Class Template
template <typename T>
class MyQueue
{
std::vector<T> data;
public: void Add(T const &d);
void Remove();
void Print();
};
10. Which of the following statements are correct? [May 2006]
int const *pi=&x;
(a) X=10;
(b) *pi=10;
(c) pi++;
(d) ++*pi;
The statements (b) and (d) are correct, since value 10 is stored in pointer variables and
preincrement of the value stored in *Pi.
11. What is dynamic initialization of objects [May 2007]
Dynamic Initialization of objects: It is initializing the objects by passing the valued to the
constructor from the user input or other means.
Through cin operator a value can be
stored in a variable and passed through a constructor this form of initializing an object is
known dynamic initialization.
12. Name few operators which can’t be overloaded using friend functions? [May
2007,May 2010]
Assignment operator =
Function call operator ( )
Subscripting operator [ ]
Class member access operator
13. What is ‘this’ pointer? How is it available to member functions of a class.
[May 2008, May 2011]
In C++ has access to its own address through an important pointer called this pointer. The
this pointer is an implicit parameter to all member functions. Therefore, inside a member
function, this may be used to refer to the invoking object.Friend functions do not have a this
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
3
pointer, because friends are not members of a class. Only member functions have a this
pointer.
14. List the use of new () and delete ().[May 2008]
The new operator is used to dynamically allocate memory on the heap. Memory
allocated by new must be deallocated using delete operator.
Syntax of new is: p_var = new type name;
where p_var is a previously declared pointer of type typename. typename can be any basic
data type.
new can also create an array:
p_var = new type [size];
In this case, size specifies the length of one-dimensional array to create.
Example 1:
int *p;
p=new int;// It allocates memory space for an integer variable
delete p;//To release the memory
15. Give the differences between function overloading and operator overloading.
[May 2008]
1.C++ allows you to specify more than one definition for a function name or an operator
in the same scope, which is called function overloading and operator overloading
respectively.
2.An overloaded declaration is a declaration that had been declared with the same name
as a previously declared declaration in the same scope, except that both declarations
have different arguments and obviously different definition (implementation).
3.The compiler determines the most appropriate definition to use by comparing the
argument types you used to call the function or operator with the parameter types
specified in the definitions. The process of selecting the most appropriate overloaded
function or operator is called overload resolution.
16. Why do you need templates. [May 2008]
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
4
Templates are a feature of the C++ programming language that allow functions and classes
to operate with generic types. This allows a function or class to work on many different data
types without being rewritten for each one. This is effectively a Turing-complete
language.Templates are of great utility to programmers in C++, especially when combined
with multiple inheritance and operator overloading. The C++ Standard Library provides many
useful functions within a framework of connected templates.
17. Write the syntax to overload the extraction and insertion operators [May 2009]
C++ is able to input and output the built-in data types using the stream extraction operator
>> and the stream insertion operator <<. The stream insertion and stream extraction
operators also can be overloaded to perform input and output for user-defined types like an
object.Here it is important to make operator overloading function a friend of the class
because it would be called without creating an object.
18. How is protected inheritance related to private inheritance? [May 2009]
The protected access specifier is similar to private access specifier for a class which is not
inherited further. The members defined as protected are accessible to member functions and
friend functions and are not available to objects. Unlike private data members,when the
class containing protected data members is inherited, the protected members are available
to derived calss member functions as well but are not available to objects of derived class.
19. How does an inline function differ from normal function [May 2010]
Inline function
1.The syntax of function declaration
Normal function
1. The syntax for it
is inline keyword used.
Inline void add(int a,int b);
2. When there is a function call,
no need of the control to transfer to
that place.Instead coding is replaced
Eg. void get();
When there is a function call,
the control is transferred to
that place.
at the function call.
20. How do friend operator functions differ from member operator function ? [May
2011]
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
5
Friend operator functions
Member operator function
1. The Syntax for it, using the
The syntax used for member
Keyword friend .
friend void add(int a,int b);
function
void display();
2. The friend function is used to access
The member function belongs
the private variable of any classes.
to that particular class
21. Why is protected access specifier needed? [May 2011]
The protected access specifier restricts access to member functions of the same class,
or those of derived classes. When a derived class inherits from a base class, the
access specifiers may change depending on the method of inheritance. There are
three different ways for classes to inherit from other classes: public, private, and
protected. There are three ways that members can be accessed:
 A class can always access it‟s own members regardless of access specifier.
 The public accesses the members of a class based on the access specifiers of that
class.
 A derived class accesses inherited members based on the access specifiers of its
immediate parent. A derived class can always access it‟s own members regardless
of access specifier.
22. What is class template? [May 2011]
Class Templates are suited can be container classes. Very famous examples for these
container classes will be the STL classes like vector, list etc., Once code is written as a C++
class template, it can support all data types.
Declaring C++ Class Templates: Declaration of C++ class template should start with the
keyword template. A parameter should be included inside angular brackets. The parameter
inside the angular brackets, can be either the keyword class or typename. This is followed
by the class body declaration with the member data and member functions. The following is
the declaration for a sample Queue class.
//Sample code snippet for C++ Class Template
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
6
template <typename T>
class MyQueue
{
std::vector<T> data;
public:
void Add(T const &d);
void Remove();
void Print();
};
23. How reusability is achieved in C++ [May 2012]
This term refers to the ability for multiple programmers to use the same written and
debugged existing class of data. This is a time saving device and adds code efficiency to the
language. Additionally, the programmer can incorporate new features to the existing class,
further developing the application and allowing users to achieve increased performance.
This time saving feature optimizes code, helps in gaining secured applications and facilitates
easier maintenance on the application.
PART – B (16 Marks)
1. (i) Explain about implementation of run time polymorphism in C++ with
example. (8) (MAY 2012)
Dynamic polymorphism refers to an entity changing its form depending on the
circumstances. A function is said to exhibit dynamic polymorphism when it exists in
more than one form, and calls to its various forms are resolved dynamically when the
program is executed. The term late binding refers to the resolution of the functions at
run-time instead of compile time. This feature increases the flexibility of the program
by allowing the appropriate method to be invoked, depending on the context.
#include"iostream.h"
#include"string.h"
#include"conio.h"
class media
{
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
7
protected:
char title[50];
float price;
public:
media(char *s,float a)
{
strcpy(title,s);
price=a;
}
virtual void display() { } //empty vitual function
};
class book:public media
{
int pages;
public:
book(char *s, float a, int p):media(s,a)
{
pages=p;
}
void display();
};
class tape:public media
{
float time;
public:
tape(char *s, float a, float t):media(s,a)
{
time=t;
}
void display();
};
void book::display()
{
cout<<"\n Title:"<
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
8
cout<<"\n Pages:"<
cout<<"\n Price:"<
}
void tape::display()
{
cout<<"\n Title:"<
cout<<"\n Play time:"<<time<<"mins";
cout<<"\n price:"<
}
int main()
{
char *title=new char[30];
float price, time;
int pages;
clrscr();
//Books details
cout<<"\n Enter Book Details\n";
cout<<"Title:";
cin>>title;
cout<<"Price :";
cin>>price;
cout<<"Pages:";
cin>>pages;
book book1(title,price,pages);
//tape Details
cout<<"\n Enter Tape Details\n";
cout<<"Title:";
cin>>title;
cout<<"Price:";
cin>>price;
cout<<"Play time (mins):";
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
9
cin>>time;
tape tape1(title,price,time);
media*list[2];
list[0]=&book1;
list[1]=&tape1;
cout<<"\n Media Details:";
cout<<"\n.........BOOK........";
list[0]->display();
cout<<"\n.....TAPE.....";
list[1]->display();
getch();
return 0;
}
(ii) Explain the types of inheritance with example.(AUC DEC 2012)
1. Single Inheritance - One base class and one derived class.
2. Multiple Inheritance - A class is derived from more than one base classes
3. Multilevel Inheritance - A sub class inherits from a class which inherits from another class.
4. Hierarchical Inheritance - More than one subclass inherited from a single base class.
1. Single Inheritance
If a single class is derived from a single base class is called single inheritance.
Eg:
Base class
Derived class
Here class A is the base class from which the class D is derived. Class D is the public
derivation of class B hence it inherits all the public members of B. But D cannot access
private members of B.
2.Multiple inheritance (C++ only)
You can derive a class from any number of base classes. Deriving a class from more
than one direct base class is called multiple inheritance.
In the following example, classes A, B, and C are direct base classes for the derived
class X:
class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X : public A, private B, public C { /* ... */ };
The following inheritance graph describes the inheritance relationships of the above
example. An arrow points to the direct base class of the class at the tail of the arrow:
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
10
The order of derivation is relevant only to determine the order of default initialization
by constructors and cleanup by destructors.
A direct base class cannot appear in the base list of a derived class more than once:
class B1 { /* ... */ }; // direct base class
class D : public B1, private B1 { /* ... */ }; // error
However, a derived class can inherit an indirect base class more than once, as shown
in the following example:
class L { /* ... */ }; // indirect base class
class B2 : public L { /* ... */ };
class B3 : public L { /* ... */ };
class D : public B2, public B3 { /* ... */ }; // valid
In the above example, class D inherits the indirect base class L once through class B2 and
once through class B3. However, this may lead to ambiguities because two subobjects of
class L exist, and both are accessible through class D. You can avoid this ambiguity by
referring to class L using a qualified class name. For example:
B2::L
or
B3::L.
You can also avoid this ambiguity by using the base specifier virtual to declare a base
class, as described in Derivation (C++ only).
3.Multilevel Inheritance
If a class is derived from a class, which in turn is derived from another class, is called
multilevel inheritance. This process can be extended to any number of levels.
4.Hierarchical Inheritance
If a number of classes are derived from a single base class then it is called
hierarchical inheritance.
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
11
2. (i) Explain the usage of template in C++. (8)
Function templates are special functions that can operate with generic types. This
allows us to create a function template whose functionality can be adapted to more
than one type or class without repeating the entire code for each type. In C++ this
can be achieved using template parameters. A template parameter is a special kind
of parameter that can be used to pass a type as argument: just like regular function
parameters can be used to pass values to a function, template parameters allow to
pass also types to a function. These function templates can use these parameters as
if they were any other regular type.
The format for declaring function templates with type parameters
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
If a set of functions or classes have the same functionality for different data types,
they becomes good candidates for being written as Templates. C++ Class Templates
are suited can be container classes. Very famous examples for these container
classes will be the STL classes like vector, list etc. Declaration of C++ class template
should start with the keyword template
//Sample code snippet for C++ Class Template
template <class T>
class mypair {
T a, b;
public:
mypair (T first, T second)
{a=first; b=second;}
T getmax ();
};
template <class T>
T mypair<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}
int main ()
{
mypair <int> myobject (100, 75);
cout << myobject.getmax();
return 0;
}
(ii) Explain how left shift and right shift operator are overloaded with example.
(AUC DEC 2012)
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
12
C++ is able to input and output the built-in data types using the stream extraction
operator >> and the stream insertion operator <<. The stream insertion and stream
extraction operators also can be overloaded to perform input and output for user-defined
types like an object.
class Distance
{
private:
int feet;
// 0 to infinite
int inches;
// 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
friend ostream &operator<<( ostream &output,
const Distance &D )
{
output << "F : " << D.feet << " I : " << D.inches;
return output;
}
friend istream &operator>>( istream
{
input >> D.feet >> D.inches;
return input;
}
&input, Distance &D )
};
int main()
{
Distance D1(11, 10), D2(5, 11), D3;
cout << "Enter the value of object : " << endl;
cin >> D3;
cout << "First Distance : " << D1 << endl;
cout << "Second Distance :" << D2 << endl;
cout << "Third Distance :" << D3 << endl;
return 0;
}
OUTPUT
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10
3. Write a C++ program to implement C=A+B, C=A-B and C=A*B where A, Band C are
objects containing a int value (vector).(AUC MAY 2012)
#include<iostream.h>
#include<conio.h>
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
13
class vector
{
int a;
public:
void getvalue()
{
cout<<"Enter the value of a:";
cin>>a;
}
vector operator+(vector ob)
{
complex t;
t.a=a+ob.a;
return(t);
}
vector operator-(vector ob)
{
complex t;
t.a=a-ob.a;
return(t);
}
vector operator*(vector ob)
{
complex t;
t.a=a*ob.a;
return(t);
}
void display()
{
cout<<a;
}
};
void main()
{
clrscr();
vector A,B,C;
A.getvalue();
B.getvalue();
C=A+B;
C.display();
C=A-B;
C.display();
C=A*B;
C.display();
getch();
}
4.
(i) Create a class that contains one data member. Overload all the four arithmetic
operators so that they operate on the objects of that class. (10)
[Refer Q.No:3]
(ii) Describe the syntax of the different forms of inheritance in C++.(6) (AUC DEC
2011)
Single Inheritance:
class A
{
public:
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
14
integer d;
};
class B : public A
{
public:
};
Multiple Inheritance:
class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X : public A, private B, public C { /* ... */ };
Multilevel Inheritance
class base_class_name
{
public:
…………….
protected:
…………….
};
class derived_class_name1 : public base_class_name
{
public:
……………
protected:
……………
};
class derived_class_name2 : public derived_class_name1
{
public:
…………….
protected:
…………….
};
5. (i) What are virtual functions? Explain with a suitable program.(10)
In OOP when a derived class inherits from a base class, an object of the derived class
may be referred to via a pointer or reference of either the base class type or the derived
class type. If there are base class methods overridden by the derived class, the method
actually called by such a reference or pointer can be bound either 'early' (by the
compiler), according to the declared type of the pointer or reference, or 'late' (i.e. by the
runtime system of the language), according to the actual type of the object referred to.
Virtual functions are resolved 'late'. If the function in question is 'virtual' in the base class,
the most-derived class's implementation of the function is called according to the actual
type of the object referred to, regardless of the declared type of the pointer or reference.
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
15
If it is not 'virtual', the method is resolved 'early' and the function called is selected
according to the declared type of the pointer or reference.
Virtual functions allow a program to call methods that don't necessarily even exist at the
moment the code is compiled.
In C++, virtual methods are declared by prepending the virtual keyword to the function's
declaration in the base class. This modifier is inherited by all implementations of that
method in derived classes, meaning that they can continue to over-ride each other and
be late-bound.
Eg:
#include<iostream.h>
#include<string.h>
class base
{
public:
int BaseInt;
};
Class derived1 : virtual public base
{
Public:
int DerivedInt;
};
Class derived2: virtual public base
{
Public:
Int Derived2Int;
};
Class DDerived : public Derived1, public Derived2
{
Public:
Int DDerivedInt2;
};
Void main()
{
DDerived DD;
DD.BaseInt=0;
DD.Derived1::BaseInt=0;
DD.Derived2::BaseInt=10;
Cout<<DD.BaseInt<<”\n”;
Cout<<DD.Derived1::BaseInt<<”\n”;
Cout<<DD.Derived1::BaseInt<<”\n”;
}
Pure virtual function or pure virtual method is a virtual function that is required to
be implemented by a derived class, if that class is not abstract. Classes containing
pure virtual methods are termed "abstract"; they cannot be instantiated directly. A
subclass of an abstract class can only be instantiated directly if all inherited pure
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
16
virtual methods have been implemented by that class or a parent class. Pure virtual
methods typically have a declaration (signature) and no definition (implementation).
As an example, an abstract base class MathSymbol may provide a pure virtual
function
doOperation(),
and
derived
classes
Plus
and
Minus
implement
doOperation() to provide concrete implementations. Implementing doOperation()
would not make sense in the MathSymbol class, as MathSymbol is an abstract
concept whose behaviour is defined solely for each given kind (subclass) of
MathSymbol. Similarly, a given subclass of MathSymbol would not be complete
without an implementation of doOperation().
Although pure virtual methods typically have no implementation in the class that
declares them, pure virtual methods in C++ are permitted to contain an
implementation in their declaring class, providing fallback or default behaviour that a
derived class can delegate to, if appropriate.
Pure virtual functions can also be used where the method declarations are being
used to define an interface - similar to what the interface keyword in Java explicitly
specifies. In such a use, derived classes will supply all implementations. In such a
design pattern, the abstract class which serves as an interface will contain only pure
virtual functions, but no data members or ordinary methods. In C++, using such
purely abstract classes as interfaces works because C++ supports multiple
inheritance. However, because many OO languages do not support multiple
inheritance, they often provide a separate interface mechanism.
(ii) What is dynamic binding? How is it achieved? (6) (AUC DEC 2011)
In OOPs Dynamic Binding refers to linking a procedure call to the code that will be
executed only at run time. The code associated with the procedure in not known until
the program is executed, which is also known as late binding.
#include <iostream.h>
int Square(int x)
{ return x*x; }
int Cube(int x)
{ return x*x*x; }
int main()
{
int x =10;
int choice;
do
{
cout << "Enter 0 for square value, 1 for cube value: ";
cin >> choice;
} while (choice < 0 || choice > 1);
int (*ptr) (int);
switch (choice)
{
case 0: ptr = Square; break;
case 1: ptr = Cube; break;
}
cout << "The result is: " << ptr(x) << endl;
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
17
return 0;
}
6. Write a C++ program as follows to perform arithmetic operations on Rational
numbers of type a/b, where a and b are integers.
(i)Define a class by ‘Rational Number’ (4)
(ii)Use operator overloaded methods for addition and subtraction (6)
(iii) Write a main program to demonstrate the use of this class and its methods
(4)
(iv) Give a sample output. (2) (AUC DEC 2010)
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
class complex
{
int i,r;
public:
void read()
{
cout<<"\nEnter Real Part:";
cin>>r;
cout<<"Enter Imaginary Part:";
cin>>i;
}
void display()
{
cout<<"\n= "<<r<<"+"<<i<<"i";
}
complex operator+(complex a2)
{
complex a;
a.r=r+a2.r;
a.i=i+a2.i;
return a;
}
complex operator-(complex a2)
{
complex a;
a.r=r-a2.r;
a.i=i-a2.i;
return a;
}
};
void main()
{
complex a,b,c;
a.read();
b.read();
c=a+b;
c=a-b;
a.display();
b.display();
c.display();
}
OUTPUT:
Enter real part: 2.5
Enter imaginary part : 3.5
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
18
Enter real part: 4.2
Enter imaginary part : 5.3
2.5+j3.5
4.2+j5.3
6.7+j8.8
7. What is meant by inheritance? Explain with examples, the various types of
inheritance supported in C++. (AUC DEC 2010)
1. Single Inheritance
If a single class is derived from a single base class is called single inheritance.
Eg:
Base class
Derived class
Here class A is the base class from which the class D is derived. Class D is the public
derivation of class B hence it inherits all the public members of B. But D cannot access
private members of B.
#include<iostream.h>
#include<conio.h>
class student
{
public:
int rno;
//float per;
char name[20];
void getdata()
{
cout<<"Enter RollNo :- \t";
cin>>rno;
cout<<"Enter Name :- \t";
cin>>name;
}
};
class marks : public student
{
public:
int m1,m2,m3,tot;
float per;
void getmarks()
{
getdata();
cout<<"Enter Marks
cin>>m1;
cout<<"Enter Marks
cin>>m2;
cout<<"Enter Marks
cin>>m3;
}
void display()
{
getmarks();
cout<<"Roll Not \t
Total \t Percentage";
1 :- \t";
2 :- \t";
2 :- \t";
Name \t Marks1 \t marks2 \t Marks3 \t
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
19
cout<<rno<<"\t"<<name<<"\t"<<m1<<"\t"<<m2<<"\t"<<m3<<"\t"<<tot<<"\t
"<<per;
}
};
void main()
{
student std;
clrscr();
std.getmarks();
std.display();
getch();
}
2.Multiple inheritance (C++ only)
You can derive a class from any number of base classes. Deriving a class from more
than one direct base class is called multiple inheritance.
In the following example, classes A, B, and C are direct base classes for the derived
class X:
class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X : public A, private B, public C { /* ... */ };
The following inheritance graph describes the inheritance relationships of the above
example. An arrow points to the direct base class of the class at the tail of the arrow:
The order of derivation is relevant only to determine the order of default initialization
by constructors and cleanup by destructors.
A direct base class cannot appear in the base list of a derived class more than once:
class B1 { /* ... */ }; // direct base class
class D : public B1, private B1 { /* ... */ }; // error
However, a derived class can inherit an indirect base class more than once, as shown
in the following example:
class L { /* ... */ }; // indirect base class
class B2 : public L { /* ... */ };
class B3 : public L { /* ... */ };
class D : public B2, public B3 { /* ... */ }; // valid
In the above example, class D inherits the indirect base class L once through class B2
and once through class B3. However, this may lead to ambiguities because two
subobjects of class L exist, and both are accessible through class D. You can avoid this
ambiguity by referring to class L using a qualified class name. For example:
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
20
B2::L
or
B3::L.
You can also avoid this ambiguity by using the base specifier virtual to declare a base
class, as described in Derivation (C++ only).
3.Multilevel Inheritance
If a class is derived from a class, which in turn is derived from another class, is called
multilevel inheritance. This process can be extended to any number of levels.
Example
class A
{
public:
void display()
{
cout<<"Base class content.";
}
};
class B : public A
{
};
class C : public B
{
};
int main()
{
C c;
c.display();
return 0;
}
OUTPUT
Base class content
8. What is type conversion? What are its types? Explain with example. [May
2007]
An assignment operation automatically does the type conversion . i.e. the type of
data to the right of an assignment operator is automatically converted to the type of the
variable on the left.
For example:
int m;
float x=3.14159;
m=x;
converts x to an integer before its value is assigned to m.
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
21
In the case of user-defined data types, conversion is difficult. Since the user-defined
data type s are designed by us to suit our requirements, the compiler does not support such
automatic type conversions.
Three types of situations might arise in the data conversion between uncompatible
types.
1. Conversion from basic type to class type
2. Conversion from class type to basic type.
3. Conversion from one class type to another.
1.Basic to class type
This is easy to accomplish. Consider the following constructor:
string::string:(char *a)
{
length=strlen(a);
p=new char[length+1];
strcpy(p,a);
}
This constructor builds a string type from a char* type variable a. the variable length
and p are data mebers of the class string. Once this constructor has been defined in the
string class, it can be used for conversion from char* type to string type. Examples:
string s1, s2;
char* nam1=”ibm pc”;
char* name2=”apple computer”;
s1=string(name1);
s2=name2;
The statement
s1=string(name1); first converts name1 from char*
type to string type and then assigns the string type values to the object s1.
The statement
s2=name2;
also does the same job by invoking the
constructor implicitly.
The following conversion statements can be used is a function.
time t1;
int duration=85;
t1=duration;
After this conversion, the hrs member of t1 will contain a value of 1 and mins member
a value of 25, denoting 1 hour and 25 minutes.
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
22
The constructors used for the type conversion take a single argument whose type is to be
converted.
2.Class to basic type
C++ allows us to define an overloaded casting operator that could be used to convert
a class type data to a basic type. The general form of an overloaded casting operator
function
is:
where V1 is an object of type vector. Both the statements have same effect.
When the compiler encounters a statement that requires the conversion of a class type to a
basic type, it quietly calls the casting operator function to do the job.
The casting operator function should satisfy the following conditions:
1. It must be a class member.
2. It must not specify a return type.
3. It must not have any arguments.
As it is a member function, it is invoked by the object and hence, the values used for
conversion inside the function belong to the object that invoked the function.
3.One Class to Another Class
There are situations arise where we would need to convert one class type data to
another class type data.
objX=objY;
//objects of different data types.
Since the conversion takes place from class Y to class x, Y is known as source class
and X is known as Destination class.
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
23
This conversion can be done by either a constructor or a conversion function. It
depends upon where we want the type-conversion function to be located in the source class
or in the destination class.
Data conversion example
In the following program,
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
24
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
25
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
26
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
27
OUTPUT
9. Illustrate unary operator overloading with example.
A minus operator when used as a unary, takes just one operand. It changes the sign of an
operand when applied to a basic data item. The program is given as follows:
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
28
The function operator-() takes no arguments. As it is member function of the same class, it
can directly access the members of the object which activated it.
It is overload a unary minus operator using a friend function as follows:
friend void operator-(space &s);
void operator-(space &s)
{
s.x = -s.x;
s.y = -s.y;
s.z = -s.z;
}
Here, the argument is passed by reference. It will not work if we pass argument by
value because only a copy of the object that activated the call is passed to operator(). Hence, the changes made inside the operator function will not reflect in the called
object.
10. Write a c++ program to get the input as String. Overload the > operator to
check if two objects are greater or not. Overload the + operator to concatenate
two objects. Overload the - operator to swap two objects.[May 2009]
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class string
{
char *name;
int length;
public:
string()
{
length=0;
name=new char[length+1];
}
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
29
string(char*s)
{
length=strlen(s);
name=new char[length+1];
strcpy(name,s);
}
void display(void)
{
cout<<name<<"\n";</name<<"\n";
}
string operator >(string &a,string &b);
void operator +(string &a,string &b);
void operator –(string &a, string &b);
};
string string::operator > (string &a,string &b)
{
length=a.length;
length1=b.length;
delete name;
name=new char[length+1];
if(strcmp(strlen(length)>atrlen(length1))
{
return a.name;
else
return b.name;
}
void string::operator + (string &a,string &b)
{
length=a.length+b.length;
delete name;
name=new char[length+1];
strcpy(name,a.name);
strcat(name,b.name);
};
void operator –(string &a, string &b);
{
String temp;
temp=new char[length+1];
length=a.length+b.length;
delete name;
name=new char[length+1];
strcpy(temp,a.name);
strcpy(a.name,b.name);
strcpy(b.name, temp);
}
void main()
{
clrscr();
string name1 ("Object ");
string name2 ("Oriented ");
string name3 ("Programming Lab");
string s1,s2,s3,s4;
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
30
s1=name1+name2;
s2=s1+name3;
if(name1>name2)
{
name1.display;
else
name2.display;
}
if(name1-name2==1)
{
name1.display();
name2.display();
else
cout<<”Not swapped”;
}
name1.display();
name2.display();
name3.display();
s1.display();
s2.display();
getch();
}
11. Write a c++ program to declare a function sum() in bas e and derived
class.Display the sum of three numbers based on whose number function is
executed.Use function concept?[May 2009]
#include<iostream.h>
#include<conio.h>
class Base
{
int a,b,c;
Base(int t1,int t2,int t3)
{
a=t1;
b=t2;
c=t3;
}
Void sum()
{
int temp;
temp=a+b+c;
cout<<temp;
}
};
class Derived : public virtual Base
{
int x,y,z;
Derived(int a1,int a2,int a3)
{
x=a1;
y=a2;
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
31
z=a3;
}
Void sum()
{
int temp;
temp=x+y+z;
cout<<temp;
}
};
Void main()
{
Base bb=Base(2,3,4);
Derived dd=Derived(7,8,9);
bb.sum();
dd.sum();
}
12. Declare a class to represent a bank account. Include data members to
represent customer name, account number, type of account,balance amount
in the account.Include member functions to assign initial values,deposit,
withdraw and display balance.Write a program to these functions.[May 2010]
#include<iostream.h>
#include<conio.h>
class bank
{
public:
char*cname;
long int acno;
void display()
{
cout<<cname;</cname;
cout<<acno;</acno;
}
};
class savings : public bank
{
public:
int wdraw, dep, bal;
void saves()
{
cout<<"Enter the amount to be deposited=Rs.";
cin>>dep;
bal+=dep;
cout<<"Enter the amount to be withdrawn=Rs.";
cin>>wdraw;
bal-=wdraw;
cout<<"Your A/c Balance is=Rs."<<bal<<endl;</bal<<endl;
}
};
class current : public savings
{
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
32
public:
void info()
{
cout<<"Last amount witdrawn=Rs."<<wdraw<<endl;</wdraw<<endl;
cout<<"Last amount deposited=Rs."<<dep<<endl;</dep<<endl;
cout<<"Your A/c Balance is=Rs."<<bal<<endl;</bal<<endl;
}};
void main()
{
int ch;
current ac;
clrscr();
cout<<"Enter customer name:";
cin>>ac.cname;
cout<<endl<<"enter a="" c="" no.:";</endl<<"enter>
cin>>ac.acno;
cout<<endl;</endl;
while(1)
{
cout<<"Enter the A/c type,1.Savings 2.Current 3.Exit\n";
cin>>ch;
switch(ch)
{
case 1:
ac.saves();
break;
case 2:
ac.info();
break;
case 3:
break;
default:
cout<<"Invalid Choice";
break;
}
if (ch==3)
break;
}
getch();
}
13. Assume the following is allowed :
Complex c1(5,4),c2(-5,4);[May 2010]
c1++;++c2;
c2=c1+c2;
c1+=c2;
c1=-c1;
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
33
cout<<c1;
Write a c++ program to perform these operations.
#include<iostream.h>
#include<conio.h>
class complex
{
float real;
float imag;
public:
complex(float tempreal=0,float tempimag=0)
{
real=tempreal;
imag=tempimag;
}
complex add(complex comp2)
{
float tempreal;
float tempimag;
tempreal=real+comp2.real;
tempimag=imag+comp2.imag;
return complex(tempreal,tempimag);
}
complex operator+(complex comp2)
{
float tempreal;
float tempimag;
tempreal=real+comp2.real;
tempimag=imag+comp2.imag;
return complex(tempreal,tempimag);
}
complex operator ++()
{
real++;
return complex(real,imag);
}
complex operator++(int dummy)
{
imag++;
return complex(real,imag);
}
complex operator ++()
{
++real;
return complex(real,imag);
}
complex operator++(int dy)
{
++imag;
return complex(real,imag);
}
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
34
void display()
{
cout<<real<<"+"<<imag<<"i\n";</real<<"+"<<imag<<"i\n";
}
};
void main()
{
getch();
complex comp1(10,20);
complex comp2(20,30);
complex compresult1,compresult2;
compresult1=comp1.add(comp2);
compresult1.display();
compresult2=comp1+comp2;
compresult2.display();
++comp1;
comp1.display();
++comp2;
comp2.display();
comp1++;
comp1.display();
comp2++;
comp2.display();
comp1+=comp2;
comp1.display();
comp1-=comp2;
comp2.dsiplay();
}
14. Give an application that fits the following inheritance hierarchy and write the
program for the same. Each class should have at least two data members and
two function members.[May 2010]
Class base
{
int rno;
string name;
public:
{
Void get()
{
Cout<<”Enter the roll number:”;
Cin>>rno;
Cout<<”Enter the student name:”;
Cin>>name;
}
Void put()
{
Cout<<”The student number is:”<<rno;
Cout<<”The student name is:”<<name;
}
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
35
};
Class Derived1 : public base
{
int mark;
string subject;
public:
base b1;
b1.get();
b1.put();
void get ()
{
Cout<<”Enter the marks:”;
Cin>>mark;
Cout<<”Enter the subject:”;
Cin>>subject;
}
Void put()
{
Cout<<”The student mark is:”<<mark;
Cout<<”The student subject is:”<<subject;
}
};
Class Derived2 : public base
{
Int sportsmark;
String event;
Public:
Derived1 D1;
D1.get();
D1.put();
void get ()
{
Cout<<”Enter the marks:”;
Cin>>sportsmark;
Cout<<”Enter the events detail:”;
Cin>>event;
}
Void put()
{
Cout<<”The student sportsmark is:”<<sportsmark;
Cout<<”The student Event detail is:”<<event;
}
};
Class DDerived : public Derived1, public Derived2
{
int age;
string curriact;
public:
Derived2 D2;
D2.get();
D2.put();
void insert()
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
36
{
Cout<<”Age:”;Cin>>age;
Cout<<”Cuuricular Activities:;cin>>curriact;
}
Void display()
{
Cout<<”The student age is:”<<age;
Cout<<”The student curricular activities:”<<curriact;
}
};
Void main()
{
DDerived DDobject;
DDobject.insert();
DDobject.display();
}
15. Discuss the rules for operator overloading.[May 2011]
Restrictions under operator overloading:
Though operator overloading is available, it is not without restrictions.Restrictions under
operator overloading are listed as follows:
1.Operators do not lose their original meaning.instead they have an additional meaning
when overloaded. One cannot change the original meaning of an operator.
2. New operators cannot be devised.Available operators with given restrictions can only be
overloaded.
3. Operators will have additional meaning,but will not have additional precedence.The
precedence remains the same to that of the original meaning.
4. Operator cannot change number of arguments,which were available in the original
form.Hence + in the binary form can only have two arguments.We cannot overload it with
three arguments.
5.Operators can only be overloaded for user-defined types. All overloaded operators must
have at least one argument as user defined type.
6. Except(), no other operator can have a default argument.
7. Some of the operators cannot be simply overloaded.
16. Create a generic base class called building that stores the number of floors a
building has ,the number of rooms, and its total square footage.Create a
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
37
derived class called house that inherits building and also stores the number of
bedrooms and the number of bathrooms.Next,create a derived class called
office that inherits building and also stores the number of fire extinguishers
and the number of telephones.[May 2011]
Class building
{
int nfloors;
int nrooms;
int foot,total;
public:
void get()
{
Cout <<”Enter the number of floors”;
Cin>>nfloors;
Cout<<”Enter the number of rooms:”;
Cin>>nrooms;
Cout<<”Enter the feet:”;
Cin>>foot;
}
Void cal()
{
int t;
t=foot/12;
Total=(nfloors*nrooms )\t;
}
Void disp()
{
Cout<<”The number of floors and rooms and the total footage:”;
Cout <<nfloors<<nrooms<<total;
}
};
Class house: public buliding
{
int nbedrooms;
int nbathrooms;
public:
void get()
{
Cout<<”Enter the number of bedrooms:”;
Cin>>nbedrooms;
Cout<<”Enter the number of bathrooms:”;
Cin>>nbathrooms;
}
Void put()
{
Cout<<”The number of bedrooms and bathrooms:”;
Cout<<nbedrooms<<nbathrooms;
}
};
Class office: public house
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
38
{
int nfireext;
int ntele;
public:
void get()
{
{
Cout<<”Enter the number of fire extinguishers:”;
Cin>>nfireext;
Cout<<”Enter the number of telephones:”;
Cin>>ntele;
}
Void put()
{
Cout<<”The number of fire extinguishers and telephones:”;
Cout<< nfireext << ntele ;
}
};
Void main()
{
Office off;
Off.get();
Off.put();
}
16. Explain stream operator overloading using friend function with example.
[May2012]
#include<iostream.h>
#include<string.h>
Class student
{
Private:
int RNo;
string name;
string Address;
public:
friend ostream & operator << (ostream & , student & );
friend ostream & operator >> (ostream & , student & );
ostream & operator << ( ostream & TempOut, student & Tempstudent)
{
TempOut<<”Roll Number is” << Tempstudent.RollNumber<<”\n”;
TempOut<<”Name is” << Tempstudent.Name<<”\n”;
TempOut<<”Address is” << Tempstudent.Address<<”\n”;
return Tempout;
}
istream & operator >>(istream & TempIn, student & Tempstudent)
{
Cout<<”Please Enter Roll Number:”;
TempIn>> Tempstudent.RollNumber;
Cout<<”\n”;
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
39
Cout<<”Please Enter the Name:”;
TempIn>> Tempstudent.Name;
Cout<<”\n”;
Cout<<”Please Enter the Address:”;
TempIn>> Tempstudent.Address;
Cout<<”\n”;
Return TempIn;
}
Void main()
{
Student captainStudent;
Cin>> CaqptainStudent;
Cout<< “Following is Captainstudent’s data \n” <<CaptainStudent<<”\n
Bye! \n;
}
CS2311 OBJECT ORIENTED PROGRAMMING / V Sem EEE – M.Sathya Asst.Prof./CSE
40
Download