Sei sulla pagina 1di 17

C++ - Object Oriented Programming – PAPER (2017 - May)

1. What is an Abstract Class?


An abstract class is, conceptually, a class that cannot be instantiated and is usually implemented
as a class that has one or more pure virtual (abstract) functions.

Sometimes implementation of all function cannot be provided in a base class because we don’t
know the implementation. Such a class is called abstract class. For example, let Shape be a base
class. We cannot provide implementation of function draw() in Shape, but we know every derived
class must have implementation of draw(). Similarly an Animal class doesn’t have implementation
of move() (assuming that all animals move), but all animals must know how to move. We cannot
create objects of abstract classes.

A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have
implementation, we only declare it. A pure virtual function is declared by assigning 0 in
declaration. See the following example.

OUTPUT:

fun() called
2. What is Implicit Conversion?

Also known as ‘automatic type conversion’.


• Done by the compiler on its own, without any external trigger from the user.
• Generally, takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid loss of data.
• All the data types of the variables are upgraded to the data type of the variable with largest
data type.
• It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).

Output:
x = 107, z = 108.000000

3. Why are Member function not virtual by default?

Member functions are not virtual by default because many classes are not designed to be used as
base classes.

Performance overhead –

Objects of a class with a virtual function require space needed by the virtual function call
mechanism - typically one word per object. This overhead can be significant, and can get in the
way of layout compatibility with data from other languages (e.g. C and Fortran).
4. What is Reflexive Association?

Sometimes objects may have a relationship with other objects of the same type. This is called
a reflexive association. A good example of a reflexive association is the relationship between a
university course and its prerequisites (which are also university courses).

Consider the simplified case where a Course can only have one prerequisite. We can do
something like this:

5. What is Reference Variable?

C++ references allow you to create a second name for the variable that you can use to read or
modify the original data stored in that variable. While this may not sound appealing at first, what
this means is that when you declare a reference and assign it a variable, it will allow you to treat
the reference exactly as though it were the original variable for the purpose of accessing and
modifying the value of the original variable--even if the second name (the reference) is located
within a different scope. This means, for instance, that if you make your function arguments
references, and you will effectively have a way to change the original data passed into the
function. This is quite different from how C++ normally works, where you have arguments to a
function copied into new variables. It also allows you to dramatically reduce the amount of
copying that takes place behind the scenes, both with functions and in other areas of C++, like
catch clauses.

OUTPUT: 56
6. Difference between new and malloc().

New/delete

• Allocate/release memory
1. Memory allocated from 'Free Store'
2. Returns a fully typed pointer.
3. new (standard version) never returns a NULL (will throw on failure)
4. Are called with Type-ID (compiler calculates the size)
5. Has a version explicitly to handle arrays.
6. Reallocating (to get more space) not handled intuitively (because of copy constructor).
7. Whether they call malloc/free is implementation defined.
8. Can add a new memory allocator to deal with low memory (set_new_handler)
9. operator new/delete can be overridden legally
10. constructor/destructor used to initialize/destroy the object

malloc/free

• Allocates/release memory
1. Memory allocated from 'Heap'
2. Returns a void*
3. Returns NULL on failure
4. Must specify the size required in bytes.
5. Allocating array requires manual calculation of space.
6. Reallocating larger chunk of memory simple (No copy constructor to worry about)
7. They will NOT call new/delete
8. No way to splice user code into the allocation sequence to help with low memory.
9. malloc/free can NOT be overridden legally

7. How are binary files different from text files?

The C++ language supports two types of files:

▪ Text files
▪ Binary files
The basic difference between text files and binary files is that in text files various character
translations are performed such as “\r+\f” is converted into “\n”, whereas in binary files no such
translations are performed.

By default, C++ opens the files in text mode.

8. What is Memory leakage?

Memory leak occurs when programmers create a memory in heap and forget to delete it.
Memory leaks are particularly serious issues for programs like daemons and servers which by
definition never terminate.
To avoid memory leaks, memory allocated on heap should always be freed when no longer
needed.

9. What is Generic Pointer?

When a variable is declared as being a pointer to type void it is known as a generic pointer. Since
you cannot have a variable of type void, the pointer will not point to any data and therefore
cannot be dereferenced. It is still a pointer though, to use it you just have to cast it to another
kind of pointer first. Hence the term Generic pointer. This is very useful when you want a pointer
to point to data of different types at different times.

For example - void *ptr


ptr is a generic pointer

Since type void is not considered as data type so ptr does not point to any data type therefore it
cannot be dereferenced.

For de-referencing you have to type cast in specific data type

For example

#include<stdio.h>
int main()
{
int a = 10;
void *ptr = &a;
printf("%d", *(int *)ptr);
return 0;
}

ptr holds the address of integer variable but for dereferencing we use type cast operator with int
data type instead of above printf statement if we write

printf("%d", *ptr);
It will throw an error

10. Difference between access specifier and access modifier.

Access Specifier: - The access specifier determines how accessible the field is to code in other
classes. Access ranges from totally accessible to totally inaccessible. You can optionally declare
a field with an access specifier keyword: public, private, or protected,default.

Access Specifier are of 4 types:


Public: - Anything declared as public can be accessed from anywhere means outside the class
accessibility will be possible
Private: - Anything declared as private cannot be accessed outside the class.
Protected: - Anything declared as protected can be accessed inside the same package and
subclasses of the different package
default: - If you not declared anything in front of any variable then it will be declared as default
automatically. Anything declared as default can be accessed only to classes in the same
package.
Access Modifier: - Access Modifier are those which change or modify the accessibility of any
variable. which gives additional meaning to data, methods and classes e.g. final cannot be
modified at any point of time.

11. What is Multiple Inheritance?

Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes.
The constructors of inherited classes are called in the same order in which they are inherited. For
example, in the following program, B’s constructor is called before A’s constructor.
12. What is default constructor?

If no constructor is defined in the class then the compiler automatically creates one for the
program. This constructor which is created by the compiler when there is no user defined
constructor and which doesn’t take any parameters is called default constructor.

Syntax:

/*.....format of default constructor..........*/


class class_name
{
.........
public:
class_name() { }; //default constructor
.........
};
13. How is encapsulation implemented in C++?

In C++ encapsulation can be implemented using Class and access modifiers. Look at the below
program:
14. Concept of Object-Oriented Programming.

Object oriented programming – As the name suggests uses objects in programming. Object
oriented programming aims to implement real world entities like inheritance, hiding,
polymorphism etc. in programming. The main aim of OOP is to bind together the data and the
functions that operates on them so that no other part of code can access this data except that
function.
Let us learn about different characteristics of an Object Oriented Programming language:
Object: Objects are basic run-time entities in an object oriented system, objects are instances of a
class these are defined user defined data types.
ex:

Object take up space in memory and have an associated address like a record in pascal or
structure or union in C.
When a program is executed the objects interact by sending messages to one another.
Each object contains data and code to manipulate the data. Objects can interact without having
to know details of each other’s data or code, it is sufficient to know the type of message accepted
and type of response returned by the objects.

15. Explain the usefulness of function templates.

Let us assume that we are in the situation where we need to create a function that
calculates the absolute value of a number.

When you have a number that is positive, then absolute value of the number is that same
number, but if the number is negative, then the absolute value of the number is that number
with sign changed.
So, the function, if you work with int data type would be like this:

int AbsolteValue( int nNumber){

return (nNumber>0) ? nNumber:-nNumber;

But, what if somebody needs the same function with double data type, instead of int? In that
case, you can create a function like the following:

double AbsoluteValue( double dNumber){

return (dNumber>0)? dNumber:-dNumber;

In the way same, we can keep creating functions reactively to cover: float, long int, long long int,
long double and so on.

There could also be a possibility when you don’t want to use the usual data types, but like to use
your own custom data type with typedef.

We cannot possibly predict all data types that our function could potentially use. In those
situations, “function templates” comes to rescue.
16. Difference between inline function and macro functions.

Macro vs Inline Function


A macro is a fragment of code, which is a
An inline function is a C++ enhancement
preprocessor directive that is included at the
feature to minimize the execution time of a
beginning of the program preceded by a hash
program.
sign.

Evaluation Time

In macro, the argument is evaluated each


In inline, the argument is evaluated once.
time it is used in the program.

Checked By

An inline function is checked by the


A macro is checked by the preprocessor.
compiler.

Keyword

Marco uses #define. The inline function uses the keyword ‘inline’.

Usage

Macro can be used to define constants,


An inline function can be used to minimize
expressions, for literal text substitution and
the execution time of the program.
to define functions etc.

Termination

Inline function terminates with the curly


Macro terminates with the new line.
brace at the end of the inline function.

Defining Point

A Marco is defined at the beginning of the An inline function can be inside or outside
program. the class.
17. What is a Nested Class?

A nested class is a class which is declared in another enclosing class. A nested class is a
member and as such has the same access rights as any other member. The members of
an enclosing class have no special access to members of a nested class; the usual access
rules shall be obeyed.

For example, the below program compiles without any error, but int y cannot be
accessed outside of the Nested class as it is private.:
18. Salient features of Structure Oriented and Object-Oriented Programming.

Structured Programming Object Oriented Programming


Structured Programming is designed which Object Oriented Programming is designed which
focuses on process/ logical structure and then focuses on data.
data required for that process.

Structured programming follows top-down Object oriented programming follows bottom-up


approach. approach.
Structured Programming is also known Object Oriented Programming supports inheritance,
as Modular Programming and a subset encapsulation, abstraction, polymorphism, etc.
of procedural programming language.

In Structured Programming, Programs are In Object Oriented Programming, Programs are


divided into small self-contained functions. divided into small entities called objects.

Structured Programming is less secure as Object Oriented Programming is more secure as


there is no way of data hiding. having data hiding feature.

Structured Programming can Object Oriented Programming can solve any complex
solve moderately complex programs. programs.

Structured Programming Object Oriented Programming provides more


provides less reusability, more function reusability, less function dependency.
dependency.

Less abstraction and less flexibility. More abstraction and more flexibility.

19. Can a Constructor be virtual?


A virtual constructor would be meaningless in C++. Declaring something virtual in C++
means that it can be overridden by a sub-class of the current class, however the
constructor is called when the objected is created, at that time you cannot be creating a
sub-class of the class, you must be creating the class so there would never be any need to
declare a constructor virtual.
And another reason is, the constructors have the same name as its class name and if we
declare constructor as virtual, then it should be redefined in its derived class with the
same name, but you cannot have the same name of two classes. So, it is not possible to
have a virtual constructor.

20. When is a template better solution than a base class??

As template is in form of generic class and generic


function so here the class and function work for all. also
in template we can change the data type of function
parameter as well as of the data member present in class.

So, A template is better solution:

1. when you are designing a generic class to contain or otherwise manage objects of other
types.
2. when the format and behavior of those other types are unimportant to their containment or
management.
3. particularly when those other types are unknown.

21. Difference between delete and delete[ ].

The delete operator deallocates memory and calls the destructor for a single object created
with new.
The delete [] operator deallocates memory and calls destructors for an array of objects created
with new [].
Using delete on a pointer returned by new [] or delete [] on a pointer returned by new results in
undefined behavior.

22. Method overriding and Method overloading. -- *Method (Function)

• Method (or a Function) Overloading


Function overloading allows us to define two or more function having the same name but with
different function body. It is useful in real world applications because practically, we encounter
such situations very commonly.

For example, if we say the word drive, we can think of driving a car, a bike or a spaceship.
Similarly Function overloading allows us to have two or more functions in a program having same
name but different signatures (a function signature is its arguments list).
• Function Overriding
Function Overriding also allows to have two or more function with the same name but in this case,
It is important to have Inheritance. When a function is already defined in the base class and we
redefine it in derived class, that function is said to be overridden. In other words, if an inherited
class contains a function with same name as that of its parent, then this concept is known
as Function Overriding. A real-world example might be: Suppose a person has a very good skills in
Classical Painting. Now, his child inherits his father’s traits and also has good painting skills but
instead he is good at Modern Art. This condition reflects Function Overriding

Potrebbero piacerti anche