0% found this document useful (0 votes)
0 views

Object Oriented Programming

Some basic question answers on OOP for CSE students in NU Bangladesh

Uploaded by

milon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Object Oriented Programming

Some basic question answers on OOP for CSE students in NU Bangladesh

Uploaded by

milon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Object Oriented Programming

CH-1

Q1. Definition of OOP (Object Oriented Programming):

Object oriented programming as an approach that provides a way of modularizing programs by creating
partitioned memory area for both data and functions that can be used as templates for creating copies of
such modules on demand. Example: C++, Smalltalk, Java.

Main features \ striking features of OOP:

o Emphasis is on data rather than procedure.


o Programs are divided into objects.
o Data structures are designed such that they characterize the objects.
o Functions that operate on the data of an object are tied together in the data structure.
o Data is hidden and cannot be accessed by external functions.
o Objects may communicate with each other through functions.
o New data and functions can be easily added whenever necessary.
o Follows bottom-up approach in program design.

Benefits of OOP:

 Through inheritance, we can eliminate redundant code and extend the use of existing classes.
 We can build programs from the standard working modules that communicate with one another,
rather than having to start writing the code from scratch, this leads to saving of development time
and higher productivity.
 The principle of data hiding helps the programmer to build secure programs that cannot be
invaded by code in other parts of the program.
 It is possible to have multiple instances of an object to co-exist without any interference.
 It is possible to map objects in the problem domain to those in the program.
 It is easy to partition the work La a project based on objects.
 The data-centered design approach enables us to capture more details of a model in
implementable form. Object-oriented systems can be easily upgraded from small to large systems.
 Message passing techniques for communication between objects makes the interface descriptions
with external systems much simpler.
 Software complexity can be easily managed.

Applications of OOP:
 Real-time systems.
 Simulation and modeling.
 Object-oriented databases.
 Hypertext, hypermedia and expert text.
 Artificial Intelligence systems and expert system.
 Neural networks and parallel programming.
 Decision support and office automation system.
 CIM/CAM/CAD systems.
Basic concepts of OOP:

Object:

Objects are the basic runtime 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.

Class:

The entire set of data and code of an object can be made a user-defined data type with the help of a class.
In fact, objects are variables of the type class. Each object is associated with the data of type class with
which they are created.

Data abstraction and encapsulation:

The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. The data is not accessible to the outside world, and only those functions which are
wrapped in the class can access it.

Abstraction, refers to the act of representing essential features without including the
background details or explanations. Classes use the concept of abstraction and are defined as a list of
abstract attributes such as size, weight and cost, and function to operate on these attributes.

Inheritance:

Inheritance is the process by which objects of one class acquire the properties of objects of
another class. It supports the concept of hierarchical classification. In OOP, the concept of inheritance
provides the idea of reusability.

Polymorphism:

Polymorphism is another important OOP concept. It means the ability to take more than one form. An
operation may exhibit different behaviors in different instances. The behavior depends upon the types of
data used in the operation.

Dynamic binding:

Binding refers to the linking of a procedure call to the code the executed in response to the
call. Dynamic binding (also known as late binding means that the code associated with a
given procedure call is not known until the time of the call at run-time.

Message passing:

An object-oriented program consists of a set of objects that communicate with each other. Those objects
communicate with one another by sending and receiving information much the same way as people pass
messages to one another.
Q2. How are data and functions organized in an object oriented programming?
Ans:
In an object oriented programming data treats as a critical element in the program development and does
not allow it to flow freely around the system. It ties data more closely to the functions that operate on it,
and protects it from accidental modification from outside functions. OOP allows decomposition of a
problem into a number of entities called objects and then builds data and functions around these objects.
The organization of data and functions in object-oriented programs is shown in Fig. The data of an object
can be accessed only by the functions associated with that object. However, functions of one object can
access the functions of other objects.

Q3. Relation between class and object:

Ans: class and objects are two different concepts but there is a relationship between them. Every object
belong to a class and every class contains one or more related objects. A class is static, so all the attributes
of class are fixed at the time of execution of a program. Objects are variables of the type class. Once a
class has been defined, we can create any number of objects belonging to that class. Each object is
associated with the data of type close with which they are created. A class is thus a collection of objects of
similar type.
For example, mango, apple and mange are members of the class fruit. Classes are user-defined data types
and behave like the built-in types of a programming language. If fruit has been defined as a class, then the
statement
fruit mango;
will create an object mango belonging to the class fruit.
The general format of the class and objects are:
class fruit
{
………..........
………………..
}; mango, orange, apple;
Q4. What is ADT?
Ans:
The meaning of ADT is Abstract Data Types. The data abstraction is the process of highlighting the essential,
inherent aspects of an entity while ignoring irrelevant details. The classes use the concept of data
abstraction, so they are known as Abstract Data Types (ADT).

Q5. Difference between OOP (Object Oriented Programming) & POP (Procedure Oriented Programming):

Object Oriented Programming Procedure Oriented Programming

1. OOP emphasis is on data. 1. POP emphasis is on algorithm.

2. Large program divided into object. 2. Large program divided into function.

3. OOP has data hiding feature. 3. POP has no such feature.

4. Follows bottom-up approach in program 4. Follows top-down approach in program


design. design.

Q6. Difference between OOP (Object-Oriented Programming) & OBP (Object-Based Programming):

Object Based Programming Object Oriented Programming


1. Object-based programming is the style of 1. Object-oriented programming is a paradigm in
programming that primarily supports which a system is modeled as a set of objects
encapsulation and object identity. that interact with each other.

2. Object-based programming do not support 2. Object-oriented programming supports


inheritance and dynamic binding. inheritance and dynamic binding.
3. Object-based programming do not support all 3. Object-oriented programming supports all the
the features of object oriented programming. features of object based programming

4. Example: Ada. 4. Example: C++, Smalltalk, Java.


Q7. Difference between Object & class:

 Objects are the basic run-time entities whereas classes are the user defined data types which
behaves like a built-in data types.
 Objects are variables of type class but class helps to make an object as user defined data type.
 An object has physical existence, but a class is a logical abstraction.

Q8. Difference between data abstraction & data encapsulation:

1. Data abstraction refers to the act of representing essential features without including the
background details. Whereas encapsulation means wrapping up of data and functions into a single
unit.
2. Data abstraction is used on class so that it can be treated like any other built-in data type. On the
other side encapsulation protects data from outside accessing.

Q9. Difference between inheritance & polymorphism:

 The mechanism of deriving a new class from an old one is called inheritance, where polymorphism
means one thing with several distinct terms.
 Inheritance provides the idea of reusability but polymorphism provides the ability to take more
than one form.

Q10. Difference between dynamic binding & massage passing:

1. Dynamic Binding refers to the linking of a procedure call to be executed in response to the call,
but Massage passing involves specifying the name of the object, the name of the function and the
information to be sent.
2. Dynamic binding is used as a function call associated with a polymorphic reference depends on
the dynamic type of that reference, whereas massage passing is the way of communicating
between objects.

CH-3

Q1. What are the applications of void data type in C++?


Ans:
The applications of void data type are:
(1) To specify the return type of a function when it is not returning any value.
(2) To indicate any empty argument list to a function.
(3) To create generic pointer.

Q2. What is the application of the scope resolution operator:: in C++?


Ans:
The application of the scope resolution operator are:
1. In the classes to identify the class to which a member function belongs.
2. To access the global version of a variable from within the inner block.
3. To avoid ambiguous situation in inheritance application.
Q3. Difference between char *const p and char const *p:
Ans:
In the statement,
char *const p;
p is declared as constant pointer. That we can not modify the address that p is initialized to.

In the statement,
char const*p;
p is declared as pointer to a constant. It can point to any variable of correct type, but the contents of what
it points to cannot be changed.

Q4. Why an array is called a derived data type?


Ans:
An array is a collection of identical data object which arc sorted consecutive memory location under a
common heading on a variable name. In the other word, an array is a group or a table of a values referred
by the same variable name. The individual values in an array are called element. Array elements are also
variable. Arrays are sets of values of the same type, which have a single name followed by index.
Whenever an array name with an index appears in an expression, the compiler assumes that element to
be of an array type. So, array is called a derived data type.

Q5. What is reference variable?


Ans:
A reference variable is a variable which provides an alias (alternative name) for previously defined
variable. Both the variables refer in the same data object in the memory. Hence, change in the value of one
will also be reflected in the value of the other variable.
For example, if we make the variable sum a reference to the variable total, then sum and total can be used
interchangeably to represent that variable, A reference variable is created as follows:
data-type & reference-name = variable-name.
For example:

float total = 100;


float & sum = total;
cout << total;
and
cout « sum;
both will print the value 100.

A major application of reference variables is in passing arguments to functions.


Q6. Discribe C++ basic data types.
Ans:
CH-4

Q1. All about inline function………………………………


Ans:
What is inline function?
An inline function is a Function that is expanded in line when it is invoked. That is, the compiler replaces
the function call with the corresponding function code.
Example:

inline double cube (double a)


{
return(a*a*a);
}

Why we make a function inline:


Every time a function is called, it takes a lot of extra time in executing a series of instructions for takes
such as jumping to the function, saving registers, pushing arguments into the stack and returning to the
calling function. When a function is small, a substantial percentage of execution time may be spent is such
overhead. To eliminate the cost of calls to small functions, inline function is used.
Advantages and Disadvantages of inline function.

When will you make a function inline? Why?


When a function contains a small number of statements, then it is declared as inline function. By declaring
a function inline the execution time can be decreased.

Advantages:
 The inline function eliminates the cost of calls of small function.
 It makes the program run faster because the overhead of a function call and return is eliminated.

Disadvantages:
 The speed benefits of inline function diminish as the function grows in size.
 It makes the program to take up more memory because the statements that define the inline
function are reproduced at each point where the function is called. So, a trade-off becomes
necessary.

Some of the situation where inline function may not work:


 For functions returning values, if a loop, a switch, or a goto exists.
 For functions not returning values, if a return statement exists.
 If functions contain static variables.
 If inline functions are recursive.

Some point about Inline Function:

 All inline function must be defined before they are called.


 The function are made inline when they are small enough to be defined in one or two lines.
Otherwise the speed benefits of inline functions diminish as the function grows in size.
 The inline keyword merely sends a request, not a command, to the compiler. The compiler may
ignore this request if the function definition is too long or too complicated and compile the
function as a normal function.
Q2. What are the advantages of function prototypes in C++?
Ans:
Function prototyping is one of the major improvements added to C++ functions. The prototype describes
the function interface to the compiler by giving details such as the number and type of arguments and the
type of return values.

Q3. What is function overloading? When do we use this concept?


Ans:
Function overloading means that we can have more than one function with the same name in our
program. The compiler matches the function call with the exact function code by checking the number and
type of the arguments. The correct function to be invoked is determined by checking the number and type
of the arguments but not on the function type.
When we need to design a family of functions with one function name but with different argument lists,
then we use this concept. The function would, perform different operations depending on the argument
list in the function call. Example:

// declaration
int add(int a, int b): // prototype 1
int add(int a, int b, int c) ; // prototype 2
double add(int p, double q): // prototype 3
// Function calls
cout add(5, 10); // uses prototype 1
cout << add(5. 10. 15) ; // uses prototype 2
cout << 5dd(15, 10.0); // uses prototype 3

Q3. What is function overriding?


Ans:
Function overriding means that derived class have the same context with same name and exactly the same
number and type of parameters and same return type as a parent/base class. Example:
class A
{
public:
void display( )
{
cout <<”A\n";
}
};
class B : public A
{
public;
void display( ) //function overriding
{
cout << "B\n”;
}
};
Q4. Difference between function overloading and function overriding:

Ans:

Function Overloading Function Overriding


1. Function overloading means that we can have 1. Function overriding means that derived class
more than one function with the same name have the same context with same name and
in our program. exactly the same number and type of
parameters and same return type as a parent
class.
2. Overloading can occur without inheritance. 2. Overriding of functions occurs when one class
is inherited from another class.
3. Overloaded functions must differ in function 3. . In overriding, function context must be same.
context, i.e. either number of parameters or
type of parameters should differ.
4. Function overloading occurs in the same 4. Function overriding occurs in different scopes.
scope.
5. Overloading is used to have same name 5. Overriding is needed when derived class
functions which behave differently depending function has to do some added or different job
upon parameters passed to them. than the base class function.

Q5. What is the ambiguous situation of function overloading?

Ans:
If an exact match is not found, the compiler uses the integral promotions to the actual arguments,
such as:
char to int
float to double
to find a match.
When either of them fails, the compiler tries to use the built-in conversions the implicit assignment
conversions to the actual arguments and then uses the function whose match is unique. If the
conversion is possible to have multiple matches, then the compiler will generate on error message.
Suppose we use the following two functions:
long square (long n)
double Square(double x)
A function call such as :
square(20)
will cause an error because int argument can be converted to either long or double, thereby creating
an ambiguous situation as to which version of square( ) should be used. If all of the steps fail, then the
compiler will try the user-defined conversions in combination with integral promotions and built-in
conversions to find a unique match.
CH-5

Q1. What is a class? How does it accomplish data hiding?


Ans:
A class is a way to bind the data and its associated functions together. It allows the data and function to be
hidden, if necessary, from external use. So in class we can declare a data as private for which the functions
outside the class cannot access the data and thus it accomplish data hiding.

Q2. How does a C++ structure differ from a C++ class?


Ans:
 C++ structure do not support data hiding concept but C++ class supports it.
 C++ structure cannot be used as built-in data types whereas C++ class do.

Q3. Describe the mechanism of accessing data members and member functions in the following cases:
(a) Inside the main program.
(b) Inside a member function of the same class.

Ans:

(a) Using object and dot membership operator. (b) Just like accessing a local variable of a
function.
Example: Example:

class Z class item


{ {
int number,code; int number;
………… float cost;
public: public:
void getdata (int a, int b) void getdata(int a, float b); //declaration
{ //inline function
number =a; //accessing data member void putdata(void) // definition inside
code=b; // the class
} {
……….. cout <<number << “\n”;
}; cout << cost <<”\n”;
}
int main() };
{
Z obj;
obj.getdata (100, 50); //accessing member function
}
Q4. What is characteristics of member functions?
Ans:
The member functions have acme special characteristics that are often used in the program development.
These characteristics are:

 Several different clauses can use the same function name. The 'membership label' will resolve their
scope.
 Member functions can access the private data of the class. A non-member function cannot do so.
 A member function can call another member function directly, without using the dot operator.

Q5. When do we declare a member of a class static?


Ans:
A data member of a class can be declared as a static and is normally used to maintain values common to
the entire class. The static member variables must be defined outside the class,
When we need a new context of a variable then we declare this variable as static.

Q6. What is friend class?


Ans:
As like friend function, we can also declare all the member functions of one class as the friend function of
another class. In this cases, the class is called a friend class. This can be specified as follows:
class Z
{
…………
…………
friend class X; //all member functions of X are friends to Z
…………
………..
};

Q7. What is local class?


Ans:
Class can be defined and used inside a function or a block. Such classes are called local classes.
Examples:
void test(int a) // function
{
………..
…………
class student // local class
{
…………
………… // local class definition
};
………..
………..
student s1(a) //create student object
}

There are some restrictions in constructing local classes. They cannot have static data members and
member functions must be defined inside the local classes. Enclosing function cannot access the private
members of a local class. However, we can achieve this by declaring the enclosing function as a friend.
Q8. What is forward declaration?
Ans:
A forward declaration is a process which allows us to tell the compiler about the existence of a class
before actually defining the class object.
In this case it allows us to tell the compiler about the existence of an object before we define the object’s
class. This way, when the compiler encounters an object, it’ll understand that we’re making a class, and
can check to ensure we’re making the class correctly, even if it doesn’t yet know how or where the object
is defined.
To write a forward declaration for a object, we use a declaration statement which is known as forward
declaration and it is a statement, so it ends with a semicolon.

Q9. How memory is allocated for object?


Ans:
The memory space for objects is allocated when they are declared and not when the class is specified. This
statement is only partly true. Actually, the member functions are created and placed in the memory space
only once when they are defined as a part of a class specification. Since all the objects belonging to that
class use the same member functions, no separate space is allocated for member functions when the
objects are created, only space for member variables is allocated separately for each object. Separate
memory locations for the object are essential, because the member variable will hold different data values
for different objects. This is shown in Fig. 5.3.

Q10. All about friend function………………………………


Ans:
What is friend function?
A friend function is a function which common to all classes. It allows the function to be made friendly with
both the classes, thereby allowing the function to have access to the private data of these classes. Such a
function need not be a member of any of these classes.
Example:
class ABC
{
……….
……….
public: friend void xyz(void); // declaration
………..
………..
};
Special characteristics of a friend function:
 It is not in the scope of the class to which it has been declared as friend.
 Since it is not in the scope of the class, it cannot be called using the object of that class.
 It can be invoked like a normal function without the help of any object.
 Unlike member functions, it cannot access the member names directly and has to use an object
name and dot membership operator with each member name (e.g. A.x).
 It can be declared either in the public or the private part of a class without affecting its meaning.
 Usually, it has the objects as arguments.

Importance of friend function:


A friend function is a non-member function that is granted access to the private member of the
class for which it is a friend. An entire class can be a friend of another class. The functions that are
declared with the keyword “friend” are known as friend function. A function can be declared as a
friend in any number of classes.

Merits and Demerits of friend function-

Merits:
 To do with operator overloading.
 The creation of certain types of I/O function.
 To have access to the private members of two or more different classes.

Demerits/Drawbacks:
 A friend function is not inherited i.e. when a base class includes a friend function, that friend
function is not a friend of a derived class.
 Although a friend function has knowledge of the private elements of the class for which it is a
friend, it can only access then through an object of the class.
 Maximum size of the memory will occupied by objects according to the size of friend members.
It breaks the data hiding concept.

When a friend function is compulsory?

We know that a non-member function cannot have an access to the private data of a class. However,
there could be a situation where we would like two classes to share a particular function. For example
consider a case where two classes manager and scientist, have been defined. We would like to use a
function income_tax( ) to operate on the objects of both these classes. In such situations, C++ allows the
common function to be made friendly with both the classes. Thereby allowing the function to have access
to the private data of these classes. Such a function need not be a member of any of these classes.
Example:
class manager
{
…………..
public:
………………….
friend income_tax( );
};
class scientist
{
…………..
public:
………………….
friend income_tax( );
};
CH-6

Q1. Distinguish between default constructor and default value/argument constructor.


Ans:
A constructor that accepts no parameters is called the default constructor. The default constructor for
class A is A::A( ). If no such constructor is defined, then the compiler supplies a default constructor.
Therefore a statement such as:
A a;
invokes the default constructor of the compiler to create the object a.
On the other hand, when we define the default constructor with arguments which has default value, then
it is called default value/argument constructor. If A is a class, then we call A::A(int x=0). For example, the
constructor complex() can be declared as follows:
complex(float real, float imag=0);
The default value of the argument imag in zero. Then, the statement
complex C(5,0):
assigns the value 5.0 to the real variable and 0.0 to imag (by default). When we called default value
constructor with no argument, then it becomes a default constructor.

Q2. What is a parameterized constructor?


Ans:
The constructors that can take arguments are called parameterized constructors. Example:
class integer
{
int m, n;
public:
integer (int x, int y) // parameterized constructor
};

Q3. Distinguish between the following two statements:


time T2(T1);
time T2 = T1;
T1 and T2 are objects of time class.

Ans:
time T2 (T1); --> explicitly called of copy constructor
time T2 = T1; --> implicitly called of copy constructor.
Q4. All about constructor………………………………

Ans:
What is constructor?
A constructor is a 'special' member function whose task is to initialize the objects of its class. It is special
because its name is the same as the class name. The constructor is invoked whenever an object of its
associated class is created. It is called constructor because it constructs the values of data members of the
class.

Advantages and disadvantages of constructor function-

Advantages:
 Constructor is used to construct the values of data members of the class.
 They are invoked automatically when the objects are created.
 They can have default arguments.
 They make 'implicit calls’ to the operators new and delete when memory allocation is required.
 When a class contains a constructor, it is guaranteed that an object created by the class will be
initialized automatically.

Disadvantages:
 They cannot be inherited, though a derived class can call the base class constructor.
 They do not have return types, not even void and therefore, and they cannot return values.
 Constructors cannot be virtual.
 We cannot defer to their addresses.
 An object with a constructor cannot be used as a member of a union.
 When a constructor is declared for a class, initialization of the class objects becomes mandatory.

The constructor functions have some special characteristics. These are:

 They should be declared in the public section.


 They arc invoked automatically when the objects are created.
 They do not have return types, not even void and therefore, and they cannot return values.
 They cannot be inherited, though a derived class can call the base class constructor.
 They can have default arguments.
 Constructors cannot be virtual.
 We cannot refer to their addresses.
 An object with a constructor cannot be used as a member of a union.
 They make 'implicit calls' to the operators new and delete when memory allocation is required.

What is copy constructor?


When a constructor accept a reference to its own class as a parameter, then the constructor is called copy
constructor. Example-
class A
{
………..
………..
public:
A(A&);
……………
…………..
};
When copy constructor is called?
Copy constructor is called on three instances:
o When declaring one object and initializing it with values from another object.
o When passing an object by value.
o When an object is returned from a function by value.

What is destructor?
A destructor, as the name implies, is used to destroy the objects that have been created by a constructor.
Like a constructor. The destructor is a member function whose name is the same as the class name but is
preceded by a tilde (~). Example:
class alpha
{
……………….
public:
alpha()
{
……………………
…………………..
}
~alpha{ }
{
…………….
…………….
};

Importance of using destructor in a class:


 It will he invoked implicitly by the compile upon exit from the program clean up storage that is no
longer accessible.
 It is a good practice to declare destructor in a program since it memory space for future use.

Deference between constructor and destructor:

Constructor Destructor
1. A constructor enables an object to initialize 1. A destructor destroyed the objects that
itself when it is created. have been created by a constructor.
2. Its name is the same as the class name. 2. Its name is the same as the class name
but is preceded by a tilde (~) sign.
3. It allocates memory space. 3. It releases memory space.
4. It will be invoked whenever an object of its 4. It will be invoked implicitly by the
associated class is created. compiler upon exit from the program to
clean up the storage.
5. Constructor can have a default argument. 5. Destructor never takes any arguments, so
it does not have any default arguments.

Note to be point:
 It is not possible to take the address of either a constructor or a destructor.
 Local objects are destroys when they go out of scope.
 Global objects are destroyed when the program ends.
 Unlike constructor functions, destructor functions cannot have parameters. The reason for this is
simple enough to understand: “There exists no mechanism by which to pass arguments to an
object that is being destroyed”.
CH-7

Q1.What is operator overloading?


Ans:
The mechanism of giving special meaning to an operator is known as operator overloading. This process is
done by operator function which syntax is:

return type class name : : operator OP (argument list)


{
function body // task defined
}

Q2. What is the process operator overloading?


Ans:
The process of overloading involves the following steps:
I. Create a class that defines the data type that is to be used in the overloading operation.
II. Declare the operator function operator op( ) in the public part of the class. It may be either a
member function or a friend function.
III. Define the operator function to implement the required operations.

Q3. What is the necessity of operator overloading?


Ans:
C++ can perform any types of operation (like +, -, *, /) in two or more built-in types data. Without operator
overloading C++ cannot perform any operation in two variables of user defined types. To provide such
arithmetic operation in two variables of user defined types with the same syntax that is applied to the basic
types. Thus, operator overloading is necessary.

Q4. State the rules for operator overloading.


Ans:
Rules for operator overloading:
 Only existing operators can be overloaded
 The overload operator must have at least one operand that is user-defined type.
 We can't change the basic meaning of an operator.
 Overloaded operators follow the syntax of the original operators.
 We can't use friend functions to overload certain
 Binary arithmetic operators such as +, -, * and / must explicitly return a value.

Q5. A friend function cannot be used to overload the assignment operator =. Explain why?
Ans:
A friend function is a non-member function of the class to which it has been defined as friend. Therefore it
just uses the functionality (functions and data) of the class. So it does not consist the implementation for that
class. That’s why it cannot be used to overload the assignment operator.
CH-8

Q1. What is inheritance?


Ans:
The mechanism of deriving a new class from an old one is called inheritance. The old class is referred to as
the base class and the new one is called derived class.

Importance of inheritance or advantages of inheritance are the following:


 Reusability of the code.
 To reduce frustration of programming.
 To increase the reliability of the code.
 To add some external instances.
 Inheritance will permit the construction of reusable software components.

Q2.How do the properties of the following two derived classes differ?


(a) class D1: private B{// ….};
(b) class D2: public B{//….};
Ans:
(a) Private member of B can not be inherited in D1. Protected member of B become private in D1. Public
member of B become private in D1.
(b) Private member of B can not be inherited in D2. Protected member of B remains protected in D2.
Public member of B remains public in D2.

Q3. What are the implications of the following two definitions?


(a) class A: public B, public C{//….};
(b) class A: public C, public B{//….};

Ans:
(a) Firstly A will inherit B and then C. Private member of B and C can not be inherited in A. Protected
member of B and C become protected in A. public member of B and C become public in A.
(b) Firstly A will inherit C and then B. Private member of C and B can not be inherited in A. Protected
member of C and B and C become protected in A. public member of C and B become public in A.

Q4. What is a virtual base class?


Ans:
When multiple paths between a bass class and a derived class are exist then this base class is virtual base
class. A base class can be made as virtual just adding ‘virtual’ keyword before this base class.

Q5. : When do we make a class virtual?


Ans:
To avoid the duplication of inherited members due to multiple paths between base and derived classes we
make base class virtual.

Q6. What is an abstract class?


Ans:
An abstract class is one that is not used to create objects. An abstract class is designed only to act as a base
class (to be inherited by other classes). It is a design concept in program development and provides a base
upon which other classes may be built.
CH-9

Q1. What is polymorphism?


Ans:
Polymorphism is a mechanism that permits the same interface to invoke different function or operators
depending upon the type of objects using the interface.

Q2. What is the advantages of polymorphism?


Ans:
Advantages of Polymorphism:
Polymorphism is the ability to treat many objects of differing but related types without regard to their
differences. In C++, polymorphism is accomplished by using class derivation and virtual functions.
Polymorphism allows client programs to be written based on the abstract interfaces of the objects which
will be manipulated. This means that future extension in the form of new types of objects is easy, if the new
objects conform to the original interface, in particular, with object-oriented polymorphism, the original
client program does not even need to be recompiled in order to make use of new types exhibiting new
behavior.

Q3. What is the Applications of ‘this’ pointer?


Ans:
The Applications of ‘this’ pointer are:

o ‘this’ unique pointer is automatically passed to a member function when it is called.


o It acts as an implicit argument to all the member functions.
o We can implicitly use the pointer this when overloading the operations using member functions.
o One important application of the pointer this is to return the objects it points to. For example, the
statement:
return *this;
inside a member function will return the object that invoked the function. This statement assumes
importance when we want to compare two or more objects inside a member function and return
the invoking object as a result.
Example:

person & person :: greater (person & x)


{
if x.age>age
return x;
else
return *this;
}
Suppose we invoke this function by the call:
max=A. greater (B);
The function will return the object B (argument object) if the age of the person B is greater than
that of A, otherwise it will return the object A(invoking object) using the pointer this.
Q4. What is virtual function?
Ans:
When we use the same function name in both the base and derived classes, the function in the base class
is declared as virtual using the keyword virtual preceding its normal declaration. A virtual function is called
via a pointer, the class of the object pointed to determine which function definition will be used. Virtual
functions implement polymorphism, whereby objects belonging to different classes can respond to the
same message in different ways.

Q5. Why do we need virtual functions?


Ans:
If we need same function name at base class and derived class then, we need virtual function.

Rules for Virtual Functions:


When virtual functions are created for implementing late binding, we should observe some basic rules
that satisfy the compiler requirements:

1. The virtual function must be members of some class.


2. They cannot be static members.
3. They are accessed by using object pointers.
4. A virtual function can be a friend of another class.
5. A virtual function in a base class must be defined, even though it may not be used.
6. The prototypes of the bate class version of a virtual function and all the derived class versions must be
identical, if two functions with the same name have different prototypes, C++ considers them as
overloaded functions, and the virtual function mechanism is ignored.
7. We cannot have virtual constructors, but we can have virtual destructors.
8. When a base pointer points to a derived class, incrementing or decrementing it will
not make it to point to the next object of the derived class. It is incremented or decremented only relative
to its base type. Therefore, we should not use this method
to move the pointer to the next object.
9. If a virtual function is defined in the base class, it need not be necessarily redefined in the derived class.
In such cases, calls will invoke the base function.

Q6. How does a virtual function help achieve run-time polymorphism?


Ans:
A virtual function supports run-time polymorphism through the base class Pointers. When a base class
pointer points to an object of a derived class containing a virtual function, the specific function called is
determined by the type of object being pointed to.

Q7. What is pure virtual function?


Ans:
A pure virtual function is a function to which the null address has been assigned. A pure virtual function
has no implementation. Such functions are called "do-nothing" functions. A “do-nothing” function may be
defined as follows:
virtual void display ( ) = 0;

Q8. When do we make a virtual function “pure”? What are the implications of making a function a pure
virtual function?
Ans:
When a function is defined as empty, then we make a virtual function “pure”, so that this function act like a
“do nothing” function.
The implications of making a function a pure virtual function is to achieve run time polymorphism.

You might also like