Você está na página 1de 7

Define object, classes and instances. Explain each with an example.

Answer
Object: Object is the basic run time entity in an Object Oriented (OO) System. From a
programmer’s perspective, it is a storage region with associated semantics. From a
designer’s perspective, it is an identifiable component in the problem domain. Object is
essentially a variable of user defined data type class.

Class: User defined data type which contains data and methods to manipulate that data; is
known as class. It is the fundamental packaging unit of OO technology. An object is a
variable of a Class. Each object is associated with the data of type class with which it is
created. Thus we can also say that class is a collection of objects of similar types. It is a
user defined data type and behaves like built-in data type of the language.

Instance: Object can also be called as runtime instance of a class. It is used to access data
and function members while a program is running. As stated earlier, class specification
provides only a template. It does not create any memory space for the object. To create
memory space at runtime, we need to create instance of the class, which is essentially the
class object.

Consider following example:

Class Student --- Class Definition


{
int rollno;
int marks;
public:
void show(int roll)
{
cout<< rollno: << marks;
}
};

void main()
{
Student s; --Object of Class
s.show();
}

Here, Student is a user defined data type - Class

In main(), variable of this user defined data type Student is created, which is the object of
that Class.

This object of class is also known as instance.


Explain data encapsulation with an example.
Answer
Data Encapsulation: The wrapping up of data and functions into a single unit (Class) is
known as Encapsulation. By encapsulating the data inside the class; data is not accessible
to the outside world. Only those functions which are wrapped inside the class can access
it. This provides protection to the data since access to it is controlled. Objects of the class
can thus access the data only using the methods provided by the class.

Class MyClass
{
int roll, marks;
public:
{
int getmarks()
{
return marks;
}
}
};

int main()
{
MyClass s;
int m;
m = s.getmarks;
}

As seen above, the class MyClass has two data members viz. roll and marks. These
members can not be accessed directly from outside the class i.e. they are encapsulated
inside the class. To access them, we need to create object of that class and invoke the data
accessing function (‘getmarks’ in this case) using that object.

What is Inheritance? Explain it with an example.


Answer
Inheritance: One of the most important features of OO design is code-reusability and it is
achieved through inheritance. Inheritance is the process by which objects of one class
acquire the properties of another class. By this we can add additional features to an
existing class without modifying it. This is possible by deriving a new class from the
existing one. The new class will have combined features of both the classes. This allows
the programmer to reuse a class that is almost, but not exactly, what he wants and change
it according to his needs.

Class Bird
{
bool has_feathers;
int legs;
public:
{
//Functions to manipulate data
}
};

Class FlyingBird : public Bird


{
int highestAltitude;
public:
{
//Functions to manipulate data
}
};

Here, Class FlyingBird is derived from Class Bird. FlyingBird has all the attributes of
Bird plus it has its own attribute highestAltitude which tells the highest altitude at which
it can fly. Bird is called as base class and FlyingBird is called as derived class.

What is Polymorphism? Explain it with an example.


Answer
Polymorphism: Poly – Multiple and Morph - Form
Polymorphism means the ability to take more than one form. An operation may exhibit
different behavior in different instances. The behavior depends on the types of data used
in the operation. For example, consider addition operation. For two numbers, the
operation will generation sum. In case of two strings, it will generate a third string with
concatenation. Thus, polymorphism allows objects with different internal structure to
share same external interface. This means that a general class of operations can be
accessed in the same manner even though specific actions associated with each operation
may differ. There are two types of polymorphism:
Compile Time Polymorphism: Achieved using operator overloading and function
overloading
Rum Time Polymorphism: Achieved using virtual functions.

Describe exceptions in C++.


Answer
Exceptions: Exceptions are certain disastrous error conditions that occur during the
execution of a program. They could be errors that cause the programs to fail or certain
conditions that lead to errors. If these run time errors are not handled by the program, OS
handles them and program terminates abruptly, which is not good. So C++ provides
Exception Handling mechanism.

Exceptions are of two types:


Synchronous Exceptions: Errors that occur due to incorrect input data or incorrect
handling of array indices (“out of range index”), memory overflow are known as
Synchronous Exceptions

Asynchronous Exceptions: The errors that are caused by events that are beyond control
of the program are Asynchronous Exceptions. E.g. Keyboard interrupts

C++ exception handling mechanism takes care of only Synchronous Exceptions.

The benefits of Exception Handling are:

1. Program is not terminated abruptly


2. User will understand what errors are occurring in the program.

The three keywords for Exception Handling are:


Try, Catch and Throw.

The program tries to do something. If it encounters some problem, it throws an exception


to another program block which catches the exception.

Consider following program code:


void main()
{
int no1, no2;
try
{
cout << “Enter two nos:”;
cin >> no1 >> no2;
if (no2 == 0)
throw “Divide by zero”;
else
throw no1/no2;
}
catch (char *s)
{
cout << s;
}
catch (int ans)
{
cout << ans;
}
}

We know that divide by zero is an exception. If user enters second no as zero, the
program throws an exception, which is caught and an error message is printed.
Please note that catch is not a function; it is a program block.

Define Templates. Give an example to illustrate it.


Answer
Templates: Templates enable us to define generic classes and generic functions. It can be
considered as a kind of macro. When an object of a specific type is defined for actual use,
the template definition for that class is substituted with the required data type. Since a
template is defined with a parameter that would be replaced by the actual data type at the
time of actual use of that function or class, templates are also sometimes called as
parameterized classes or parameterized functions.

e.g. a class template for an array class would enable us to create arrays of various data
types such as int array or float array.

A template for function swap() would help us create different versions of swap() to swap
2 ints, 2 floats etc.

Consider swap() function:

template <class T>


void swap (T &a, T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}

The call: swap (i, j) would replace the T with datatype of first parameter (ie i in this case)

Template for class:


template <class T>
class stack
{
T data[max];
int top;
public:
stack()
{
top = -1;
}
void push(T item)
{
// Code to push item on stack
}
T pop()
{
// Code to pop topmost item of the stack
}
};

Following calls would create stacks of different data types:


stack <int> s1;
stack <char> s2;
etc.

What is Namespaces? Provide an example for it.


Answer
Namespaces: The basic purpose of Namespaces is to reduce name clashes that occur with
multiple, independently developed libraries. It can be defined as a declarative region that
can be used to package names, improve program readability, and reduce name clashes in
the global namespace. They facilitate building large systems by partitioning names into
logical groupings.

namespace school
{
class UpperKG
{
};
class LowerKG
{
};
void Admit()
{
}
// Other code in the namespace
}

Consider another example where two namespaces contain same name:


namespace A
{
int x = 3;
int z = 4;
}
namespace B
{
int y = 2;
int z = 4;
}

int add()
{
int sum;
sum = A::x + B::z;
return sum;
}

Here, the scope resolution operator (::) specifies the namespace from where variable z is
to be used. Another way of achieving this is ‘using’ directive as follows:

int add()
{
using B::z;
using A::x;
int sum = x + z;
return sum;
}

Você também pode gostar