Anda di halaman 1dari 15

OBJECT ORIENTED METHODOLOGY(SUM-2015)

1(A).What Does Class mean in C++?

Ans:- It is a user defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A class is like a blueprint
for an object.
Exp-Fruit mango (Here Fruit is class )
1(b)What is Object Oriented Programming? How it is different from procedure oriented
programming?

Ans:--> Object-oriented programming (OOP) refers to a type of computer programming


(software design) in which programmers define not only the data type of a data structure, but
also the types of operations (functions) that can be applied to the data structure.

Procedure Oriented Programming Object Oriented Programming


In POP, program is divided into small In OOP, program is divided into parts
Divided Into
parts called functions. called objects.
In OOP, Importance is given to the
In POP,Importance is not given to data
data rather than procedures or
Importance but to functions as well as sequence of
functions because it works as a real
actions to be done.
world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access OOP has access specifiers named
POP does not have any access specifier.
Specifiers Public, Private, Protected, etc.
In OOP, objects can move and
In POP, Data can move freely from
Data Moving communicate with each other through
function to function in the system.
member functions.
To add new data and function in POP is OOP provides an easy way to add new
Expansion
not so easy. data and function.
In OOP, data can not move easily from
In POP, Most function uses Global data
function to function,it can be kept
Data Access for sharing that can be accessed freely
public or private so we can control the
from function to function in the system.
access of data.
POP does not have any proper way for OOP provides Data Hiding so provides
Data Hiding
hiding data so it is less secure. more security.
In OOP, overloading is possible in the
Overloading In POP, Overloading is not possible. form of Function Overloading and
Operator Overloading.
Example of POP are : C, VB, Example of OOP are : C++, JAVA,
Examples
FORTRAN, Pascal. VB.NET, C#.NET.
1(c). Distinguish the following term:

(i) Data abstraction and Data Encapsulation


Ans:- -> Encapsulate means to hide. Encapsulation is also called data hiding.You
can think Encapsulation like a capsule (medicine tablet) which hides medicine
inside it. Encapsulation is wrapping, just hiding properties and methods.
Encapsulation is used for hide the code and data in a single unit to protect the
data from the outside the world. Class is the best example of encapsulation.

-> Abstraction refers to showing only the necessary details to the intended user.
As the name suggests, abstraction is the "abstract form of anything". We use
abstraction in programming languages to make abstract class. Abstract class
represents abstract view of methods and properties of class.

Abstraction is implemented using interface and abstract class while Encapsulation


is implemented using private and protected access modifier.

2. OOPS makes use of encapsulation to enforce the integrity of a type (i.e. to make
sure data is used in an appropriate manner) by preventing programmers from
accessing data in a non-intended manner. Through encapsulation, only a
predetermined group of functions can access the data. The collective term for
datatypes and operations (methods) bundled together with access restrictions
(public/private, etc.) is a class.

3. Example of Encapsulation

Class Encapsulation
{
private int marks;

public int Marks


{
get { return marks; }
set { marks = value;}
}
}

4. Example of Abstraction

abstract class Abstraction


{
public abstract void doAbstraction();
}

public class AbstractionImpl: Abstraction


{
public void doAbstraction()
{
//Implement it
}
}
2(a). What is a reference variable?

Ans:- When a variable is declared as reference, it becomes an alternative name for an


existing variable. A variable can be declared as reference by putting ‘&’ in the declaration.
#include<iostream>
int main()
{
int x = 10;

// ref is a reference to x.
int& ref = x;

// Value of x is now changed to 20


ref = 20;
cout << "x = " << x << endl ;

// Value of x is now changed to 30


x = 30;
cout << "ref = " << ref << endl ;

return 0;
}
2(b). Describe the basic data types used in C++ with suitable Example?

Ans- While writing program in any language, you need to use various variables to store various information.
Variables are nothing but reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory.

You may like to store information of various data types like character, wide character, integer, floating point,
double floating point, boolean etc. Based on the data type of a variable, the operating system allocates memory
and decides what can be stored in the reserved memory.

Primitive Built-in Types


C++ offers the programmer a rich assortment of built-in as well as user defined data types. Following table
lists down seven basic C++ data types −

Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating point double
Valueless void
Wide character wchar_t

Several of the basic types can be modified using one or more of these type modifiers −

 signed
 unsigned
 short
 long
The following table shows the variable type, how much memory it takes to store the value in memory, and
what is maximum and minimum value which can be stored in such type of variables.

Type Typical Bit Width Typical Range


char 1byte -127 to 127 or 0 to 255
unsigned char 1byte 0 to 255
signed char 1byte -127 to 127
int 4bytes -2147483648 to 2147483647
unsigned int 4bytes 0 to 4294967295
signed int 4bytes -2147483648 to 2147483647
short int 2bytes -32768 to 32767
unsigned short int Range 0 to 65,535
signed short int Range -32768 to 32767
long int 4bytes -2,147,483,648 to 2,147,483,647
signed long int 4bytes same as long int
unsigned long int 4bytes 0 to 4,294,967,295
float 4bytes +/- 3.4e +/- 38 (~7 digits)
double 8bytes +/- 1.7e +/- 308 (~15 digits)
long double 8bytes +/- 1.7e +/- 308 (~15 digits)
wchar_t 2 or 4 bytes 1 wide character

The size of variables might be different from those shown in the above table, depending on the compiler and
the computer you are using.

Following is the example, which will produce correct size of various data types on your computer.

#include <iostream>
using namespace std;

int main() {
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;

return 0;
}

This example uses endl, which inserts a new-line character after every line and << operator is being used to
pass multiple values out to the screen. We are also using sizeof() operator to get size of various data types.

When the above code is compiled and executed, it produces the following result which can vary from machine
to machine −

Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4
typedef Declarations
You can create a new name for an existing type using typedef. Following is the simple syntax to define a new
type using typedef −

typedef type newname;

For example, the following tells the compiler that feet is another name for int −

typedef int feet;

Now, the following declaration is perfectly legal and creates an integer variable called distance −

feet distance;

Enumerated Types
An enumerated type declares an optional type name and a set of zero or more identifiers that can be used as
values of the type. Each enumerator is a constant whose type is the enumeration.

Creating an enumeration requires the use of the keyword enum. The general form of an enumeration type is −

enum enum-name { list of names } var-list;

Here, the enum-name is the enumeration's type name. The list of names is comma separated.

For example, the following code defines an enumeration of colors called colors and the variable c of type color.
Finally, c is assigned the value "blue".

enum color { red, green, blue } c;


c = blue;

By default, the value of the first name is 0, the second name has the value 1, and the third has the value 2, and
so on. But you can give a name, a specific value by adding an initializer. For example, in the following
enumeration, green will have the value 5.

enum color { red, green = 5, blue };

2(c).write a program to print the following output in c++.


#include <iostream>
void numpat(int n)
{
int num = 1;

for (int i=0; i<n; i++)


{
num = 1;
for (int j=0; j<=i; j++ )
{
cout << num << " ";
num = num + 1;
}
cout << endl;
}
}
int main()
{
int n = 5;
numpat(n);
return 0;
}

3(a).What is the application of scope resolution operator in c++?

Ans:- The scope resolution operator helps to identify and specify the context to which an identifier refers, particularly by
specifying a namespace. The specific uses vary across different programming languages with the notions of scoping. In many
languages the scope resolution operator is written "::".

3(b). The process of initializing variable at the time of its declaration at run time is known as dynamic initialization
of variable.
Thus in dynamic initialization of variable a variable is assigned value at run time at the time of its declaration.

Example:
int main()
{
int a;
cout << “Enter Value of a”;
cin >> a;
int cube = a * a * a;
}

In above example variable cube is initialized at run time using expression a * a * a at the time of its declaration.

3(c). Describe the characteristics of a static member variable .Write a c++ program using static
data member?

Ans:- C++ introduces two more uses for the static keyword when applied to classes: static member variables, and
static member functions. Fortunately, these uses are fairly straightforward. We’ll talk about static member variables
in this lesson, and static member functions in the next.

Before we go into the static keyword as applied to member variables, first consider the following class:

#include<iostream.h>
1 class Something
2 {
3 public:
4 int m_value = 1;
5 };
6
7 int main()
8 {
9 Something first;
10 Something second;
11
12 first.m_value = 2;
13
14 std::cout << first.m_value << '\n';
15 std::cout << second.m_value << '\n';
16
17 return 0;
18 }
When we instantiate a class object, each object gets its own copy of all normal member variables. In this case,
because we have declared two Something class objects, we end up with two copies of m_value: first.m_value, and
second.m_value. first.m_value is distinct from second.m_value. Consequently, the program above prints:

4(a) What is manipulator?Name two manipulators which are frequently used in c++?
Ans:-

C++ offers the several input/output manipulators for formatting, commonly used manipulators are given
below..

Manipulator Declaration in
endl iostream.h
setw iomanip.h
setprecision iomanip.h
setf iomanip.h
4(b).When will you make a function inline?Why?Write a program in c++ using an inline
function?
Ans:- I know that inline is a hint or request to compiler and its used to avoid function call overheads.
->The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be
instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being
called.
Syntax Of Inline Function
inline return_type function_name(arguments...)
{
//function_code
return_value;
}

Example:-
#include<iostream.h>
#include<conio.h>

class line {
public:
inline float mul(float x, float y) {
return (x * y);
}
inline float cube(float x) {
return (x * x * x);
}
};

void main() {
line obj;
float val1, val2;
clrscr();
cout << "Enter two values:";
cin >> val1>>val2;
cout << "\nMultiplication value is:" << obj.mul(val1, val2);
cout << "\n\nCube value is :" << obj.cube(val1) << "\t" <<
obj.cube(val2);
getch();
}
4(c) Dynamic initialization of object refers to initializing the objects at run time i.e. the initial value of an
object is to be provided during run time. Dynamic initialization can be achieved using constructors and
passing parameters values to the constructors. This type of initialization is required to initialize the class
variables during run time.
Need of dynamic initialization
Dynamic initialization of objects is needed as
 It utilizes memory efficiently.
 Various initialization formats can be provided using overloaded constructors.
 It has the flexibility of using different formats of data at run time considering the situation.
Program example to explain the concept of dynamic initialization
#include <iostream>

using namespace std;

class simple_interest
{
float principle , time, rate ,interest;

public:
simple_interest (float a, float b, float c) {
principle = a;
time =b;
rate = c;
}
void display ( ) {
interest =(principle* rate* time)/100;
cout<<"interest ="<<interest ;
}
};

int main(){

float p,r,t;

cout<<"principle amount, time and rate"<<endl;


cout<<"2000 7.5 2"<<endl;

simple_interest s1(2000,7.5,2);//dynamic initialization

s1.display();

return 1;
}
5(a)What is a constructor? Is it mandatory to use a constructor in a class?
Ans:- A constructor is a member function of a class which initializes objects of a class. In C++,Constructor is automatically
called when object(instance of class) create. It is special member function of the class.
->We know that C++ class constructor is called when we create an object of a class. If a class is not required to initialize its
data member or does not contain data member, there is no need to write empty constructor explicitly. ... In below class,
default constructor will be called on object creation of the class.
5(b)Define Destructor. Describe the importance of Destructor?
-> A destructor is a special method called automatically during the destruction of an object. Actions executed in the
destructor include the following: Recovering the heap space allocated during the lifetime of an object. Closing file or
database connections. Releasing network resources.
-> Destructors are used for reinitializing the objects which are initialized by the
constructors. With the help of destructors, the objects are destroyed. This special member
function is called automatically when an object is destroyed. A Destructor function also has
the same name as that of the class but it is preceded by a ~, symbol.
-> Destructors have the opposite function of a constructor. The main use
of destructors is to release dynamic allocated memory. Destructors are
used to free memory, release resources and to perform other clean up.
Destructors are automatically named when an object is destroyed. Like
constructors, destructors also take the same name as that of the class
name.
-> You use destructor to do things that are not handled by the garbage collector like closing a database
connection, freeing a file locking, closing socket or any other methods of remote connections, etc.
-> A destructor is a special member function of a class. it is invoked automatically whenever an object of the
class goes out of scope, i.e., gets 'destroyed'. thus destructors provide a useful way to do things you might want
to while winding up, like freeing up memory, closing database connections, network connections etc. like a
constructor, a destructor does not have a return type, but unlike a constructor, it does not take any
arguments.

5(C)What is an operator function?Describe the syntax of an operator function.Also write a


program in c++ explaining unary operator overloading?
Ans:-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. ... The process of selecting
the most appropriate overloaded function or operator is called overload resolution.
Operator overloading is an important concept in C++. It is a type of polymorphism in which an operator is
overloaded to give user defined meaning to it. Overloaded operator is used to perform operation on user-
defined data type. For example '+' operator can be overloaded to perform addition on various data types, like
for Integer, String(concatenation) etc.

Almost any operator can be overloaded in C++. However there are few operator which can not be overloaded.
Operator that are not overloaded are follows
 scope operator - ::
 sizeof
 member selector - .
 member pointer selector - *
 ternary operator - ?:
Operator Overloading Syntax
Example:-
#include<iostream.h>
#include<conio.h>

class complex {
int a, b, c;
public:

complex() {
}

void getvalue() {
cout << "Enter the Two Numbers:";
cin >> a>>b;
}

void operator++() {
a = ++a;
b = ++b;
}

void operator--() {
a = --a;
b = --b;
}

void display() {
cout << a << "+\t" << b << "i" << endl;
}
};

void main() {
clrscr();
complex obj;
obj.getvalue();
obj++;
cout << "Increment Complex Number\n";
obj.display();
obj--;
cout << "Decrement Complex Number\n";
obj.display();
getch();
}

6(a) What is a virtual base class?


An ambiguity can arise when several paths exist to a class from the same
base class. This means that a child class could have duplicate sets of
members inherited from a single base class.
- C++ solves this issue by introducing a virtual base class. When a class is
made virtual, necessary care is taken so that the duplication is avoided
regardless of the number of paths that exist to the child class.
6(b) What does Inheritance mean in c++?What are the different forms
of inheritance?Brefly explain
Ans:- Types of Inheritance
In C++, we have 5 different types of Inheritance. Namely,

1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)

Single Inheritance
In this type of inheritance one derived class inherits from only one base class. It is the most
simplest form of Inheritance.

Multiple Inheritance
In this type of inheritance a single derived class may inherit from two or more than two base
classes.

Hierarchical Inheritance
In this type of inheritance, multiple derived classes inherits from a single base class.

Multilevel Inheritance
In this type of inheritance the derived class inherits from a class, which in turn inherits from
some other class. The Super class for one, is sub class for the other.
Hybrid (Virtual) Inheritance
Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance.

6(c)What does Polymorphism mean in c++?How is it achieved (i)at compile time and (ii)at run
time .Write a program in c++ to show the run time polymorphism.
Ans:- The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of
classes and they are related by inheritance. C++ polymorphism means that a call to a member function will cause a different
function to be executed depending on the type of object that invokes the function.

Compile time Polymorphism Run time Polymorphism


In Compile time Polymorphism, call is In Run time Polymorphism, call is not resolved
resolved by the compiler. by the compiler.
It is also known as Static binding, Early It is also known as Dynamic binding, Late
binding and overloading as well. binding and overriding as well.
Overloading is compile time polymorphism Overriding is run time polymorphism having
where more than one methods share the same same method with same parameters or
name with different parameters or signature signature, but associated in a class & its
and different return type. subclass.
It is achieved by function overloading and It is achieved by virtual functions and
operator overloading. pointers.
It provides fast execution because known early It provides slow execution as compare to early
at compile time. binding because it is known at runtime.
Compile time polymorphism is less flexible as Run time polymorphism is more flexible as all
all things execute at compile time. things execute at run time.
Example:-
#include<iostream>
using namespace std;

class Base
{
public:
virtual void show() { cout<<" In Base \n"; }
};

class Derived: public Base


{
public:
void show() { cout<<"In Derived \n"; }
};
int main(void)
{
Base *bp = new Derived;
bp->show(); // RUN-TIME POLYMORPHISM
return 0;
}

7(a)What is an Exception?
Ans:- A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C++ exception
handling is built upon three keywords: try, catch, and throw.
7(b) Define Template ?and Distinguish between class template and function
template?
Ans:- Differences between Class and Function Templates

The name of a template class is a compound name consisting of the template name and the full template argument
list enclosed in angle braces. Any references to a template class must use this complete name. For example:

template <class T, int range> class ex


{
T a;
int r;
// ...
};
//...
ex<double,20> obj1; // valid
ex<double> obj2; // error
ex obj3; // error

C++ requires this explicit naming convention to ensure that the appropriate class can be generated.

A template function, on the other hand, has the name of its function template and the particular function chosen to
resolve a given template function call is determined by the type of the calling arguments. In the following example,
the call min(a,b) is effectively a call to min(int a, int b), and the call min(af, bf) is effectively a call to min(float a,
float b):

// This example illustrates a template function.

template<class T> T min(T a, T b)


{
if (a < b)
return a;
else
return b;
}
void main()
{
int a = 0;
int b = 2;
float af = 3.1;
float bf = 2.9;
cout << "Here is the smaller int " << min(a,b) << endl;
cout << "Here is the smaller float " << min(af, bf) << endl;
}

7(c)Describe various classes for file operations.Write a program in C++ to open a file with constructor function.
Ans:- The C++ I/O system contains a hierarchy of classes that are used to define various streams to deal with
both the console and disk files. This classes are called String Classes. These classes are declared in the header
file iostream.This file should be included in all the programs that communicate with the console unit.

Stream classes for console I/O operations

ios is the base class for istream(input stream)and ostream(output stream) which are ,in turn, base classes for
iostream(input/output stream).The class ios is declared as the virtual base class so that only one copy of its
members are inherited by the iostream.
The class ios provides the basic support for formatted and unformatted I/O operations. The class
istream provides the facilities for formatted and unformatted input while the class ostream provides the
facilities for formatted and unformatted output. The class iostream provides the facility for handling both
input and output streams. Three classes,namely,istream_withassign,ostream_withassign and
iostream_withassign add assignment operators these classes.

ios (General input/output stream class)

1. Contains basic facilities that are used by all other input and output classes.
2. Also contains a pointer to a buffer object(streambuf object).
3. Declares constants and functions that are necessary for handling formatted input and output
operation.

istream(input stream)

1. Inherits the properties of ios


2. Declares input functions such as get(),getline() and read().
3. Contains overloaded extraction operator.

ostream(output stream)

1. Inherits the properties of ios


2. Declares output functions such as put() and write().
3. Contains overloaded initiation operator.

iostream(input/output stream)
1. Inherits the properties of ios istream and ostream through multiple inheritance and thus contains all
the input and output functions.

Streambuf

1. Provides an interface to physical devices through buffers.

Acts as a base for filebuf class used ios files.

#include<conio.h>
#include<string.h>
#include<stdio.h>
#include<fstream.h>
#include<stdlib.h>
void main()
{
ofstream fout;
ifstream fin;
char fname[20];
char rec[80], ch;
clrscr();

cout<<"Enter file name: ";


cin.get(fname, 20);

fout.open(fname, ios::out);

if(!fout)
{
cout<<"Error in opening the file "<<fname;
getch();
exit(1);
}
cin.get(ch);

cout<<"\nEnter a line to store in the file:\n";


cin.get(rec, 80);
fout<<rec<<"\n";
cout<<"\nThe entered line stored in the file successfully..!!";
cout<<"\nPress any key to see...\n";
getch();
fout.close();

fin.open(fname, ios::in);
if(!fin)
{
cout<<"Error in opening the file "<<fname;
cout<<"\nPress any key to exit...";
getch();
exit(2);
}

cin.get(ch);
fin.get(rec, 80);
cout<<"\nThe file contains:\n";
cout<<rec;
cout<<"\n\nPress any key to exit...\n";
fin.close();

getch();
}

Anda mungkin juga menyukai