Você está na página 1de 17

ANSWERS FOR ASSIGNMENTS OF II SEMESTER MCA

OOPS Using C + + - 01
2) What is function overloading ? Write a C++ program to implement a function overloaded.
There can be more than one user defined functions which have same name and perform
different operations. This is a powerful feature of C++ ,which is known as Function overloading.
Every overloaded function should however have a prototype.
Program to implement a function overloaded:Printline ( )
//fnoverload.cpp
#include <iostream.h>
void printline ( );
void printline (char ch);
void printline (char ch, int n);
void main ( )
{
printline ( );
printline (*);
printline (*,20);
}
void printline ( );
{
For (int i = 0;i<25; i++)
cout<< ;
cout<<endl;

}
void printline (char ch);
{
for (int I = 0;i<25;i++)
cout<<ch;
cout<<endl;
}
void printline (char ch,int n);
{
for (int i =0;i<n;i++)
cout<<ch;
cout<<endl;
}
3) Discuss the constructors and destructors with suitable example
Constructors and destructors have got a very important place as components of a class.
Constructors are member functions of a class which have same name as the
class name. Constructors are called automatically whenever an object of the class is created. This
feature makes it very useful to initialize the class data members whenever a new object is created.
It also can perform any other function that needs to be performed for all the objects of the class
without explicity specifying it.
Destructors on the other hand are also member functions with the same name
as class but are prefixed with tilde (-) sign to differentiate it from the constructor. They are invoked
automatically whenever the objects life expires or it is destroyed. It can be used to return the
memory back to the operating system if the memory was dynamically allocated.

Example for implementing constructor and destructor.://constdest.cpp


# include <iostream.h>
class sample
{
private:
int data;
public:
sample ( )
{data = 0; cout <<Constructor invoked,,endl;
}
~sample ( )
{
Cout <<destructor invoked;
}
void display ( )
{
cout << Data = <<daya<< endl;
};
void main ( )
{
sample obj 1;
obj.display ( );
}

The output will be Constructor invoked


Data = 0
Destructor invoked.
4) What do you mean by operator overloading? Illustrate with suitable example for
overloading Unary Operators.
In C++ programming Operator overloading is an interesting feature. This is a feature that allows
programmers to specify how various arithmatic, relational and many other operators work with
user defined datatypes or classes. It provides a flexible way to work with classes and can make
program code look obvious. Operator Overloading helps to use the default operators with the user
defined objects for making the code simpler.
Several operators such as dot operator ( .). scope resolution (: operator, conditional operator (?:)
etc cannot be overloaded. When using operator overloading, the operator should perform only the
most obvious function. Otherwise it will lead to more confusion. If you are overloading + operator
for distance class it should add 2 distance objects and should not do something else. However
some syntactical charestrestics of operators cannot be changed even if you want to.
Therefore operator overloading should be used for a class where it is required to perform obvious
functions with the default operators and there can be no other meaning for the same.
Unary operators are those operators which work on one operator. Some of the unary operators are
++, --, and minus (-). Operators overloading works similar to any member function of a class. But
it is not invoked using dot operator. Just like member function the operator has a return value and
takes arguments. It is invoked by the operand which uses. But in Unary Operators, the calling
operand can be either left or right of the operator like in case of increment and decrement
operators. While defining the operator functionality for the class the keyword operator is used.
Example for overloading Unary Operators:// unary.cpp
# include <iostream.h>
class counter
{
Unsigned int count;
public;

counter ( )
{
count = 0;
}
int getcount ( )
{
return count;
}
void operator ++ ( )
{
count ++;
}
};
void main ( )
{
counter c1;
c1++;
++c1;
cout<<c1.getcount ( );
}
Here the operator ++ is defined to return void and take no arguments. All Unary operators do not
take no arguments as it operates on only one operand and that operand itself invokes the operator.
Therefor the operator is sent by default.

1) Distinguish between Procedural Language and OOP Language. And


explain the key feature of OOP
The programming language has come out from machine language, assembly languages to
High level languages. High level languages are C, Basic, Fortran are very easy in learning as it
deals with more English like keywords, compared to machine and assembly languages. These
high level languages are known as Procedural Languages as each an every statement in the
program had to specified to instruct the computer to do a specific job. The Procedural languages
focused on organizing program statements into procedures or functions. Larger programs were
either broken into functions or modules which had defined purpose and interface to other
functions.
Procedural approach for programming had some problems as the size of the sofwares grew larger
and larger. Here the data will be completely forgotten. Data in the program was created by
variables and if more than one functions had to access data, global variables were used. the
global variable concept here leads to difficulty in debugging and modifying the program when
several functions access a particular data.
Procedural languages had limitations of extensibility as there was limited support for creating
user defined datatypes and defining how these data types will be handled.
The Object oriented approach overcomes this problem by modeling data and functions together
there by allowing only certain functions to access the required data. This program provides the
flexibility through the class.
In procedural language, the program model is not closer to real world objects. But in object
oriented approach, this will be solved further by conceptualizing the problem as group of objects
which have their own specific data and functionality.
Key features of OOP:The key features are as follows
a) Objects and Classes
An Object is a program of some real world thing, i.e a person, place or an event.
Objects can have both attributes (data) and behaviours (functions or methods). Attributs
describe the object with respect to certain parameters and Behaviours or functions describe
the functionality of the object.. Objects can be any one of these followingExternal entities
Things
Occurrence or events

Roles
Organisational units, places and Data structure.
Objets with the same data structure and behaviour are grouped together as class. That means
Objects are instances of a class. Classes are templates that provide definition to the objects of
similar type. Objects are like variables created whenever necessary in the program. We can create
as many objects of a class.
b) Encapsulation
Encapsulation is a mechanism that binds the properties and behaviour into a single
unit. Data and functions are said to be encapsulated in an single entity as object. The data is said
to be hidden thus not allowing accidental modification.
c) Abstraction
Abstraction is one type of mechanism that hides the background details of the object.
d) Inheritence
This is one of the most powerful features of OOP languages that allows you to derive
a class from existing one. Here we can inherit the properties and behaviour from existing class to
derived class. Normally existing class is base class and the derived classis the new class.
e) Polymorphism
Polymorphism is a mechanism that provides ability to take more than one form in an
object.Operator overloading is a kind of polymorphism. Operator overloading
features allows users to define how basic operators work with objects. The operator +
will be adding 2 numbers when used with integer variables. However when used with
user defined string class, + operator may concatenate two strings.

7) Write a C++ program to demonstrate a complete implementation of class template


stack.
//stack.h
# pragma once
template <class T>
class Stack
{
public:
Stack (int = 10);

~Stack ( )
{
delete [ ] stack Ptr;
}
int push (const T &);
int pop (T&); // pop an element off the stack
int is Empty ( ) const
{
return top = = -1;
}
int isFull ( ) const
{
return top = = -1;
}
private:
int size; // Number of elements on Stack
int top;
T*stackPtr;
};
//constructor with the default size 10
template <class T>
Stack <T>: :Stack (int s)
{
size = s > 0 & & s < 1000 ? s: 10;

top = -1; // initialize stack


stackPtr = new T [size];
}
// push an element onto the Stack
template <class T>
int Stack <T> : :push (const T & item)
{
if (! isFull( ) )
{
stackPtr[++top] = item;
return 1; // push successful
}
return 0; // push unsuccessful
}
//pop an element off the Stack
template <class T>
int Stack <T> : :pop(T&popValue)
{
if(!isEmpty ( ) )
{
popValue = stackPtr[top--];
return 1; //pop successful
}
return 0; // pop unsuccessful

}
6) Difference between a static member function and non static member functions with
appropriate example
The difference between a static member function and non-static member functions are as
follows:a) A static member function can be called, even when a class is not instantiated, a non-static
member function can be called only after instantiating the class as an object.
b) A static member function can access only static member data,static member
functions and data and functions outside the class. A non-static member function
can access all of the above including the static class data member.
c) A static member function cannot be declared virtual, whereas a non-static member
functions can be declared virtual.
d) A static member function cannot have access to the thispointer of the class.
e) The stati member functions are not used very frequently in programs. But they
nevertheless, they become useful whenever we need to have functions which are
accessible even when the class is not instantiated.
We cannot have static and non-static member functions with the same names and the
same number and types of areguments.
Like static data members, you may access a static member function f( ) of a class A
without using an object of class A.
Example of Static member function:
# include <iostram.h>
using namespace std;
stuct X
{
private:
int i;
static int si;
public:
void set_i( int arg)
{

10

i = arg;
}
void print_i ( )
{
cout << Value of i = <<i<<endl;
cout << Again, value of i = <<this->i<<endl;
}
static void print_si ( )
{
cout <<Value of si = <<si<<endl;
//cout << Again, value of si = <<this->si <<endl;
}
};
int X : :si = 77;
//intialize static member data
int mail ( ) {
X xobj;
xobj.set_i ( 11);
xobj.print_i ( );
//static data members and functions being to the class and
// can be accessed without using an object of class X
X : :print_si ( );
X :: set_si ( 22);
X ::print_si ( );
}
Here the out put will be like thisValue of i = 11
Then again the value of i = 11
Value of si = 77
Then again the value of si = 22

11

Example for a non-static member function:


Here the non-static member function printall ( ) calls the static member function f( )
using this pointer
#include <iostream>
using namespace std;
Class C {
static void f( ) {
cout <<Here is i: <<i <<endl;
}
static int i ;
int j;
public:
C(int firstj): j(firstj) { }
void printall ( );
};
void C ::printall ( ) {
cout << Here is j: <<this->j << endl;
this->f( );
}
int C::i = 5
int main ( ) {
C obj_C(0);
obj_C.printall( );
}
The output for this will be as follows:
Here j : 0
i: 5

12

8) What is template specialization? Describe a scenario in which template


class partial specialization is considered appropriate

Some times in some of the cases it is possible to override the template generated code by
providing special definitions for specific types. This is called template specialization.

Scenario for template class partial specialization;// base template class


template<typename T1,typename T2>
class X {
};
int main ( )
{
//generates an instruction from the base template
X<char, char> xcc;
//generates an instantiation from the partial specialization
x<char, int> xii;
return 0;
}
A partial specialization matches a given actual template argument list if the template arguments
of the partial specialization can be deduced from the actual template argument list.

13

5) Write a C++ program which demonstrates the difference between static and dynamic
binding.

The first program demonstrates static binding:#include<iostream>


using namespace std;
struct A{
void f ( ) { cout << ClassA << endl;}
};
struct B: A {
void f ( ) { cout << Class b << endl;}
};
void g(A& arg) {
arg.f ( );
}
int main ( ) {
B x;
g(x);
}

The output for the above example will beClass A


When the function g ( ) is called, function A::f( ) is called, although the argument refers to an
object of type B. At compile time, the compiler knows only that the argument of function g( )
will be a reference to an object derived from A; it cannot determine whether the argument wil

14

be a reference to an object of type A or type B. However, this can be determined at run time.
This ex. is same as above except that A::f ( ) is declared with the virtual keyword.
#include <iosstream>
using namespace std;
struct A {
virtual void f ( ) { cout <<Class A<< endl; }
}
struct B: A {
void f ( ) { cout << Class B << endl; }
};
void g(A& arg) {
arg.f ( );
}
int main ( ) {
B x;
g (x);
}
The output will be as follows:
Class B
the virtual keyword indicates to the compiler that it should choose the appropriate definition of f ( ) not by
the type of reference, but by the type ob object that the reference refers to..
15

16

17

Você também pode gostar