Assignment Oops

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

Assignment

of
Object oriented programming with C++

Submitted by:
DEEPIKA
05504092018
MCA 1st yr.

Q1. Explain the procedure for creating input and


output object.
Ans.These two keywords coutand cin are used very often
for taking inputs and printing outputs. These two are the
most basic methods of taking input and output in C++.
For using cin and cout we must include the header
file iostream in our program.
The objects defined in the header file iostream like cin
and cout.
1. Standard output stream (cout): Usually the standard
output device is the display screen. cout is the instance
of the ostream class. cout is used to produce output on
the standard output device which is usually the display
screen. The data needed to be displayed on the screen
is inserted in the standard output stream (cout) using
the insertion operator (<<).
Eg.:
#include <iostream>
usingnamespacestd;
intmain( ) {
charsample[] = "John-";
cout << sample << " –Sheen";
return0;
}
Output:
John-Sheen
2.Standard input stream (cin): Usually the input device
is the keyboard. cin is the instance of theclass
istream and is used to read input from the standard
input device which is usually keyboard.
The extraction operator(>>) is used along with the
object cin for reading inputs. The extraction operator
extracts the data from the object cinwhich is entered
using the keboard.
Eg.:
#include<iostream>
usingnamespacestd;
intmain()
{ intage;
cout << "Enter your age:";
cin >> age;
cout << "\nYour age is:
"<<age;
return0;
}
Output:

Q2. What are static objects?


Ans.An object become static when static keyword is used
in its declaration. example:

First statement when executes creates object on stack


means storage is allocated on stack. Stack based objects
are also called automatic objects or local objects. static
object are initialized only once and live until the program
terminates. Local object is created each time its
declaration is encountered in the execution of program.
Q3. How class can be changed into another class
type?
Ans.Through class conversion, one can assign data that
belongs to a particular class type to an object that belongs
to another class type.
Example:
Let there be two classes ‘A’ and ‘B’. If we want to
allocate the details that belong to class ‘A’ to an object of
class ‘B’ then this can be achieved by –

Q4. What are virtual destructors?


Ans. Deleting a derived class object using a pointer to a
base class that has a non-virtual destructor results in
undefined behaviour. To correct this situation, the base
class should be defined with a virtual destructor. For
example, following program results in undefined
behaviour.
#include<iostream>
using namespace std;
class base {
public:
base()
{ cout<<"Constructing base \n"; }
~base()
{ cout<<"Destructing base \n"; }
};
class derived: public base {

public:
derived()
{ cout<<"Constructing derived \n"; }
~derived()
{ cout<<"Destructing derived \n"; }
};
int main(void)
{
derived *d = new derived();
base *b = d;
delete b;
getchar()void
return 0;

Making base class destructor virtual guarantees that the


object of derived class is destructed properly, i.e., both
base class and derived class destructors are called.
} #in

Q5. What is object slicing in C++?


Ans.A derived class object can be assigned to a base class
object, but the other way is not possible.
class Base { int x, y; };
class Derived : public Base { int z, w; };
int main()
{
Derived d;
Base b = d;
}
Object slicing happens when a derived class object is
assigned to a base class object, additional attributes of a
derived class object are sliced off to form the base class
object.
#include <iostream>
using namespace std;
class Base
{
protected:
int i;
public:
Base(int a) { i = a; }
virtual void display()
{ cout << "I am Base class object, i = " << i << endl; }
};
class Derived : public Base
{
int j;
public:
Derived(int a, int b) : Base(a) { j = b; }
virtual void display()
{ cout << "I am Derived class object, i = "
<< i << ", j = " << j << endl; }
};
void somefunc (Base obj)
{
obj.display();
ob
int main()
{
Base b(33);
Derived d(45, 54);
somefunc(b);
somefunc(d);
return 0;

Q6. What are vptr and vtable ?


Ans.To implement virtual functions,use a special form of
late binding known as the virtual table or vTable.
The virtual table is a lookup table of functions used to
resolve function calls in a dynamic/late binding manner.
Every class that uses virtual functions (or is derived from
a class that uses virtual functions) is given its own virtual
table.
This table is simply a static array that the compiler creates
at compile time. A virtual table contains one entry for
each virtual function that can be called by objects of the
class.
Each entry in this vTable is simply a Function Pointer that
points to the most-derived function accessible by that
class i.e. the most Base Class.

vPtr is set (automatically) when a class instance is created


so that it points to the virtual table for that class. *__vPtr
is inherited by derived classes.
Q7. What are Explicit and Implicit conversion?
Ans.Implicit type conversion happens when the
compiler is expecting a value of one type but is given a
value another type.
Eg:
#include <iostream>
using namespace std;
int main()
{
int x = 10;
char y = 'a';
x = x + y;
float z = x + 1.0;
cout << "x = " << x << endl
<< "y = " << y << endl
<< "z = " << z << endl;

return 0;
}
Output:
x = 107
y=a
z = 108

Explicit type conversionhappens when the user uses


a type cast to convert a value from one typeto
another type.
Eg.:-
#include <iostream>
using namespace std;
int main()
{ double x = 1.2;
int sum = (int)x + 1;
cout << "Sum = " << sum;
return 0;
}
Output:
Sum = 2

Q8. What do you mean by object delegation?


Ans.Delegation is simply passing a duty off
tosomeone/something else.
 Delegation can be an alternative to inheritance.
 Delegation means that you use an object of another
class as an instance variable, and forward messages to
the instance.
 It is better than inheritance for many cases because it
makes you to think about each message you forward,
because the instance is of a known class, rather than a
new class, and because it doesn’t force you to accept
all the methods of the super class: you can provide
only the methods that really make sense.
 Delegation can be viewed as a relationship between
objects where one object forwards certain method calls
to another object, called its delegate.
 The primary advantage of delegation is run-time
flexibility – the delegate can easily be changed at run-
time. But unlike inheritance, delegation is not directly
supported by most popular object-oriented languages,
and it doesn’t facilitate dynamic polymorphism.

Q9. Illustrate two ways to open a file.


Ans.Opening of files can be achieved in the following
two ways :
1. Using the constructor function of the stream class.
2. Using the function open().
The first method is preferred when a single file is used
with a stream. However, for managing multiple files with
the same stream, the second method is preferred. Let's
discuss each of these methods one by one.
Opening File Using Constructors
We know that a constructor of class initializes an object of
its class when it (the object) is being created. Same way,
the constructors of stream classes (ifstream, ofstream, or
fstream) are used to initialize file stream objects with the
filenames passed to them.
Eg:-
ifstream fin("myfile", ios::in) ;

The above given statement creates an object, fin, of input


file stream. The object name is a user-defined name (i.e.,
any valid identifier name can be given). After creating the
ifstream object fin, the file myfile is opened and attached
to the input stream, fin. Now, both the data being read
from myfile has been channelised through the input
stream object

Opening Files Using Open() Function


There may be situations requiring a program to open more
than one file. The strategy for opening multiple files
depends upon how they will be used. If the situation
requires simultaneous processing of two files, then you
need to create a separate stream for each file. However, if
the situation demands sequential processing of files (i.e.,
processing them one by one), then you can open a single
stream and associate it with each file in turn. To use this
approach, declare a stream object without initializing it,
then use a second statement to associate the stream with a
file. For example,
ifstream fin; // create an input stream
fin.open("Master.dat", ios::in); // associate fin stream with file Master.dat
: // process Master.dat
fin.close(); // terminate association with Master.dat

fin.open("Tran.dat", ios::in); // associate fin stream with file Tran.dat


: // process Tran.dat
fin.close();
The above code lets you handle reading two files in
succession. Note that the first file is closed before opening
the second one. This is necessary because a stream can be
connected to only one file at a time.

Q10. Differentiate pointer to a constant and constant


to a pointer.
Ans.
No Pointer to constant Constant pointers
.
1. *ptr=20 statement is invalid *ptr=20 is absolutely valid in
in pointer to constant . i.e. constant pointers. i.e.
assigning value is illegal. assigning value is perfectely
legal.
2. Ptr++ statement is valid in Ptr++ statement is invalid in
pointer to constant. constant pointers.
3. Pointer can be incremented Pointer cannot be
and decremented. incremented and
decremented.
4. Pointrer is pointing to Constant pointer is pointing
constant data object. to data objects.
5. Declaration : const int *ptr; Declaration: int *const ptr;

Q11. Explain the features of object oriented


programming.
Ans. Features of object oriented programming are:
1. Emphasis is on data rather than procedure.
2. Program are divided into what are known as
objects.
3. Data structures are designed such that they
characterize the objects.
4. Functions that operate on the data of an object are
tied together in the data structures
5. Data is hidden and cannot be accessed by external
functions.
6. Objects may communicate with each other through
functions.
7. New data and functions can be easily added
whenever necessary.
Q12. How is garbage collection is done in C++ ?
Ans. Garbage collection comes under memory
management. It is systematic recovery of storage which
was earlier being used but now it is no longer
needed.Garbage collection is an automatic memory
management feature in many modern programming
languages.
when the program has no more references to that Object,
the Object's memory becomes unreachable, but it is not
immediately freed. The Garbage Collection checks to see
if there are any Objects in the heap that are no longer
being used by the application. In C , we use free()
function and in C++ delete() function is used.
Advantages:-
1) It makes our system memory efficient by de-referring
process which are no longer in use.
2) No requirement of extra application for cleaning
memory.

Q13. Write a program to determine what fraction


of a given text is consists of vowels.
Ans. #include<iostream>
#include<string>
//#include<set>
using namespace std;
int main(){
string s;
getline(cin,s);
int vowel=0;
for(int i=0;i<s.length();i++){
if (tolower(s[i])=='a' || tolower(s[i])=='e' ||
tolower(s[i])=='i' || tolower(s[i])=='o' || tolower(s[i])=='u')
{
vowel++;}
}
cout<<"fraction of vowel to word
is"<<vowel<<"/"<<s.length();
}

Q14. What do you mean by generic classes ?


Give examples.
Ans.Generic classes are those which describe the
functionality without being bound to any data type. These
classes can be used to generate definitions of classes
which are bound to a particular data type. A good example
is an Array class. Functionality of array class will be the
same irrespective of whether the array members are int,
float or string.
class Stack[A] {
private var elements: List[A] = Nil
def push(x: A) { elements = x :: elements }
def peek: A = elements.head
def pop(): A = {
val currentTop = peek
elements = elements.tail
currentTop
}
}
-This implementation of a Stack class takes any type A as
a parameter. This means the underlying list, var elements:
List[A] = Nil, can only store elements of type A. The
procedure def push only accepts objects of
type A(note: elements = x ::
elements reassigns elements to a new list created by
prepending x to the current elements).

Usage
To use a generic class, put the type in the square brackets
in place of A.
val stack = new Stack[Int]
stack.push(1)
stack.push(2)
println(stack.pop) // prints 2
println(stack.pop) // prints 1
The instance stack can only take Ints. However, if the type
argument had subtypes, those could be passed in:
class Fruit
class Apple extends Fruit
class Banana extends Fruit
val stack = new Stack[Fruit]
val apple = new Apple
val banana = new Banana
stack.push(apple)
stack.push(banana)
Class Apple and Banana both extend Fruit so we can push
instances apple and banana onto the stack of Fruit.
Note: subtyping of generic types is invariant. This means
that if we have a stack of characters of
type Stack[Char] then it cannot be used as an integer stack
of type Stack[Int]. This would be unsound because it
would enable us to enter true integers into the character
stack. To conclude, Stack[A] is only a subtype
of Stack[B] if and only if B = A. Since this can be quite
restrictive, type parameter annotation mechanism to
control the subtyping behavior of generic types.

You might also like