Featured

bcs-031 solved assignment

BCS-031

(a) What is Object Oriented Programming? Explain its features with example.
sol-object oriented programming is a programming methodology where the main emphasis is given on the object or the data and not on the functions or operations that operate the data .data is undervalued in procedural programming. here the design puts the data upfront and organisation of data is significant area .
features of the oop

  • objects-: you approach a programming problems in an object-oriented language you are no longer ask how the problem will be divided into functions, but how it will be divided into object. thinking in terms object, rather than functions has a surprisingly helpful effect on how easily program can be designed.this result from the close match between object in the programming sense and object in the real world.                                                          physical objects                                                                                                               1 automobiles in a traffic-flow simulation                                                                         2 Electrical components in a circuit design program.                                                       3 Aircraft in an traffic-controll system                                                                        Elements of the computer user-environment                                                                         1 The mouse and the keyboard.                                                                                     2 windows                                                                                                                     3 menus                                                                                                                         4 graphic objects(lines,rectangles,circles)                                                                 the match between programming objects and real-world object the happy result of combining data and functions:the resulting object offer a revolution in a program design .no such close match between programming construct and the items being modeled exist in a procedural language

  •     classes-:in oop we say that objects are the member of classes.Almost all the computer-language have built-in datatypes.for instance a data type int.meaning integer, is predefined in c++ you can declared as many variable of types int as you need in your programs                                                                                                                        int marks;                                                                                                                      int no_of_assignments;                                                                                                    int no_of_papers;
ex class Box
{
   public:
      double length;   // Length of a box
      double breadth;  // Breadth of a box
      double height;   // Height of a box
};
a class serve as a plan,or templates. it specifies what data and what function will be included in object of that class.defining the class doesn't create any variables.A class is thus a collection of similar objects. this fits our non technical understanding of class of mountaineers. there is no one person called mountaneerrs But specifiers people with specific names are members of this class if they posses certain characteristics.
 INHERITANCE-:the idea  of classes leads to the idea of inheritance. In our daily lives, we use the concept of classes being divided into sub classes. we know that the class of animals is divided into mammals , amphibians, insects, bird, and so on. The class of vehicles is divided cars, trucks , buses, and motorcycles .principle in this sort of division is that each subclass shares common characteristics with the class from which its derived. cars, trucks buses and motorcycles all have wheels and a motor; these are the defining characteristics of vehicles. In addition to the characteristics: buses ,for instance ,have  seats for many people ,while trucks have space for large loads
for ex-
class employee
{
int id_number;
char nam_of_employee[25];
int age;
char department_name[25];
int salary;
char address[25];
//member functions
void display_name(void);
void display_id(void);
void raise_salry(float percent);
};
class manager
{
public:
int id_number;
char name_of_employee[25];
int age;
char department_name[25];
int salary;
char address[25];
char name_of_seceratory[25];
employee*team_members;
void display_name(void);
void display_id(void);
void display_seceratory_name(void);
void raise_salary(float percent);
};






Polymorphism &overloading-: using operators or functions in different way, depending on what they are operating is called polymorphism. one thing with several distinct forms. When  an existing operator , such as + or = is given the capability to operate new data type, it is said to be overloading.   Overloading   is a kind of   polymorphism; it is also an important feature of oop.

Encapsulation and data hiding -:  the property of being a self-contained unit is called encapsulation. The idea that the encapsulated unit can be used without knowing how it works is called data hiding.  Encapsulation is   principle by which related contents of a system are kept together. It   minimizes   traffic between   different   parts of the work and it separates certain specific requirements   from other   parts of specification, which use those requirements. The important advantage of using encapsulation is that it helps to minimize  rework when developing a new system . The part of the works  which is prone to change ,can be encapsulated together .Thus any changes can be made  without affecting the overall  system and hence changes be easily incorporated .When an engineer need to add resistor to the device she is creating , she doesn’t typically build a new  one from the scratch .She walks over to a  bin of resistors , examine the bin of resistors , examines the color bands that indicate the properties and indicate the properties , and picks the one she needs . The resistors is a “black box”  as far as the engineer is concerned- that is , she doesn’t care how it does it’s work as long as it conforms to her specifications. All the resistors properties are encapsulated in the resistor object- they are not spread out through the circuitry. It is not necessary to understand how the resistor works to use it effective, because its data is hidden inside the resistor covering.
c) Explain the usage of the following   c++  operator .with the help of example of program.
a)Relational operator-:the relational operators  are used to test  the relation between two values. All relational operators are binary operators and therefore require two operands. . A relational expression return zero when the relation is false and a non zero when it is true.
Operator
Meaning
Example
         
==
Equal to
5==5
!=
Not equal to
5!=7
> 
Greater than
7>5
< 
Less than
8<9
>=
Greater than or equal to
8>=8
<=
Less than or equal to
9<=9

b)LOGICAL OPERATOR-: The(!) operator is the c++  operator to perform the Boolean operation NOT. It has only one operand, located at its right, and the only thing that it does is to inverse the value of it , producing false if its operand is true and true if its operand is false. Basically, it return the opposite Boolean value of evaluating its operand .Logical operator of c++
Operator
Meaning
&&
Logical AND
II
Logical OR
!
Logical NOT
To understand the use of this operator in c++  , let us take following example:
!(5==5)//evaluate to false because the expression at its right(5==5) is true
!(6<=4) //evaluate to true  because (6<=4) would be false .
!true //evaluate to false
!false // evaluate to true.
The logical operator && and II are used when evaluating two expression to obtain a single relational result. The operator && corresponds with the Boolean logical operation AND. this operations result true if two operands are true and false otherwise .

Operands(a)
Operands(b)
Result
True
True
True
True
False
False
False
True
False
False
False
 False
          The operator II corresponds with the Boolean logical operation OR corresponds with the Boolean logical operations OR. This operations results true if either one of its two operands is true, thus being false only when both operands are false themselves .to understand the use II OR operator , let us take the possible results of a II b
Operand(a)
Operand(b)
Operand(c)
True
True
True
True
False
True
False
True
True
False
False
false
Example ((5==5)&&(3>6))// evaluates to false (true && false)
 ((5==5)II (3>6))//evaluates to true (true II false).


Scope resolution operator(::) is used to define a function outside a class or when we want to use a global variable but also has a local variable with same name.
C++ programming code
#include <iostream>
using namespace std;

char c = 'a';     // global variable

int main() {
  char c = 'b';   //local variable

  cout << "Local c: " << c << "\n";     
  cout << "Global c: " << ::c << "\n";  //using scope resolution operator

  return 0;
}
Scope resolution operator in class
#include <iostream>
using namespace std;

class programming {
public:
  void output();  //function declaration
};

// function definition outside the class

void programming::output() {
  cout << "Function defined outside the class.\n";
}

int main() {
  programming x;
  x.output();

  return 0;
Q-2
(b)Explain the following terms in the context of object oriented programming also explain how   these concepts are implemented in C++ by giving an example program for each. (6 Marks)
(a) Virtual Function
(b) Operator Overloading
Ans )in object oriented programming , a virtual function or virtual method is a function whose behavior, by virtue of being declared “virtual” is determined by the definition of a function with the same signature furthest in the inheritance lineage of the instanitiated object on which it is called. This concept  is a very important part of  the polymorphism portion of object oriented programming (OOP).The concept of the virtual function solve the following problem :
In OOP when a derived class  inherits  from a base class , an object of the derive class may be referred to (or cast) as either being the base class type of the derive class type . if there are base class function  overridden by the derived class, a problem than arise  when a derived object has been cast as the base class type . when a derived object is referred to to as being of the base type, the desired function call behavior is ambiguous.
For example a base class animal could have a virtual function eat subclass fish would implement eat() differently than subclass Wolf, but you can invoke eat() on any class instance referred to as animal, and get the eat() on any class instance referred to as animal , and get the eat(0 behaviour of the specific subclass.
Ex
# include<iostream.h>
Class Animal
{
Public:
Virtual void eat`(){std::cout<<”I eat like a generic Animal\n”;}
};
Class wolf :public Animal
{public:
Void eat(){std::cout<<”I eat like a fish!\n”;}
};
Class Fish : public Animal
{
Void eat(){std::cout<<”I eat like afish!\n;}
};
Class other Animal:public Animal
{
};
Int main()
{
Animal *anAnimal[4];
anAnimal[0]=new Animal();
anAnimal[1]=new wolf();
anAnimal[2]=new fish();
anAnimal[3]=new otherAnimal();
for(int i=0;i<4;i++)
anAnimal[i]->eat();
}
Output with the virtual method eat:
I eat like a generic Animal.
I eat like a Wolf.
I eat like a fish.
I eat like generic Animal.
Output without the virtual method eat:
I eat like A GENERIC Animal.
I eat like a generic Animal.
I eat like  a generic Animal.
I eat like a generic Animal
OPERATOR OVERLOADING-: operator overloading is extremely powerful and use ful feature of object oriented programming. In c++ you can overload any of the built-in operators ,such as + or* to suit particular applications.example  imagine that you are running a  restaurants and you want to write a program to handle your billing print your menus and so on. We create a menu item class:
Class Menuitem
{
Private:
Float price;
Char name[40;
Public:
Menuitem::Menuitem{float itemprice,char*itemName);
Float Menuitem::Getprice(void);
};
Your program could define a menutime object for each item on the menu. When some one orders you’d calculate the bill by adding together the price of each Menuitem like this:
Menuitem chicken(8.99,”chicken tandoori”);
Menuitem wine(2.99,”tandoor”);
Float total;
Total=chicken->Getprice()+wine->getprice();
This particular diner had the chicken and a glass of wine. The total is calculated usingthe member function Getprice()
Operator overloading provides an alternative way of totaling up the bill.
Total=chicken+wine;
By adding the price of chicken to the price of wine.
In c++ you can “reprogram” this operation by giving the+ operator a new meaning. To do this, we need to create a function to overload the + operator.
Float operator+(Menuitem item1,Menuitem item2)
{
Return(item1.Getprice()+ item2.Getprice());
}
Notice the name of this new function. Any function whose name follows the form
Operator<c++ operator>
Is said to overload the specified operators. When you overload an operator you are asking the compiler to call your function instead of interpreting the operator as it normally would.
Calling an operator overloading function
When the compiler calls an overloading function, it maps the operator’s operands to the function parameters. For example, suppose the function:
Float operator+(Menuitem item1,Menuitem item2)
{
Return(item1.Getprice()+item2.Getprice());
}
Is used to overload the + operator. When the compiler encounters the expression chicken+ wine it class operator+(), passing chicken as the first parameters and wines as the second parameter.operator+()’s return value is used as the result of the expression.


Q-3 what is polymorphism? What are different form of polymorphism? Explain implementation of polymorphism with the help of a c++ program.
Ans)Using operator and functions in different ways depending upon what they are operated open is called polymorphism.there are 3 types of  polymorphism
1.    Function overloading
2.    Operator overloading
3.    Virtual function
It has been implemented in c++ using functions.
·         In function overloading we have different number of arguments and different types  of arguments and different types of arguments with same functions name, ie. Same form not forming different functions
·         Operator overloading helps  to operate on user defined data type(ie depending upon what they are operated on).
·         Virtual function: allow same function name in different cases.
These program can be manipulated using a single statement in main function.
Eg
Shape*arr[50];
For(i=0;i<50;i++)
Arr[1]->draw();
//different function of draw functions are
//called depending upon arr[i] contents.
#include <iostream> 
using namespace std;
 
class Shape {
   protected:
      int width, height;
   public:
      Shape( int a=0, int b=0)
      {
         width = a;
         height = b;
      }
      int area()
      {
         cout << "Parent class area :" <<endl;
         return 0;
      }
};
class Rectangle: public Shape{
   public:
      Rectangle( int a=0, int b=0):Shape(a, b) { }
      int area ()
      { 
         cout << "Rectangle class area :" <<endl;
         return (width * height); 
      }
};
class Triangle: public Shape{
   public:
      Triangle( int a=0, int b=0):Shape(a, b) { }
      int area ()
      { 
         cout << "Triangle class area :" <<endl;
         return (width * height / 2); 
      }
};
// Main function for the program
int main( )
{
   Shape *shape;
   Rectangle rec(10,7);
   Triangle  tri(10,5);

   // store the address of Rectangle
   shape = &rec;
   // call rectangle area.
   shape->area();

   // store the address of Triangle
   shape = &tri;
   // call triangle area.
   shape->area();
   
   return 0;
}

 B)what is access control specifier? Explain the need of different access control specifier with example.
We need different access specifier:Any class can inherit from any other class, but it is not necessarily good practice to deo so . in heritance should be usedf when you have more general class of object tat describes a set of objects. The features of every element of the set(of every object that is also of the more general type) should be reflected in the more general class. This class is called the base class. Base class usually contain functions that all the classes. Inheriting from it , known as derived classes, will need . base class should also have all the variables that every derived class would otherwise contain.
Now outlook at an example of how to structure a program with several classes. Take a program used to simulate the interaction between types of organism,trees, birds, bears, and other creatures inhabiting a forest. We have base classes for the animals and the plants . then we want classes for specific type of animals :pigeons and vultures, bears and lions, and specific types of plants:oak and pine, grass and flower.
The classes shares data. Aderived class has access to most of the functions and variables of the base class. There are however , ways to keep a derived class from accessing some attributes of its base class. The keyword public, protected , and private are used to control access to information within a class. It is important to remember that public protected control information both for specific instances of classes and for classes as general data type . variables and functions designated public are both inherited by derived classes and accessible to outside functions and code when they are elements of a specific instance of a class. Protected variables are not accessible by functions and code outside the class, but derived class  inherit these functions and variables  as part of their own class. Private variables are neither accessible outside the class when it is specific class nor are available to derived classes.    
 Q -4
(A)
 Explain the concept of copy constructor with the help of  an example of program.
A copy constructor is used to declare and initialize an object from another object .for example , the statement
Integer11(10);
Would define the object 11 and the same time initialize it to the value of 10. Another form of this statement is
Integer 12 =11;
Thus the process of initializing through a copy constructor is known as copy initialization. A copy constructor is always used to when compiler has to create a temporary object of a class object. The copy constructors are used in the following situations
·          The initialization of an object by another object of the same class
·         Return of objects as a function value.
·         Stating the object as by value parameters of a function.
The syntax of copy constructor is
Class_name:: class_name(class_name&ptr)
// overloading class constructors
#include<iostream.h>
Using namespace std;
Class CRectangle
{
Int width, height;
Public:
CRectangle();l
CRectangle(int,int);
Int area (void
{
Return(width*height);
}
};
CRectangle::CRectangle()
{
Width=5;
Height=5;
}
CRectangle::CRectangle(int a, int b)
{width=a;
Height=b;
}
Int main()
{CRectangle rect(3,4);
CRectangle rectb;
Cout<<”rect area:’<<rect.area()<<endl;
Cout<<”rectb area:”<<rectb.area()<<endl;
Return0;
}
Output:
Rect area:12
Rectb area:25


b)what is an exception ? how is an exception is different   from an error explain advantage of exception handling in c++ , with the help of example of an program.

Ans The term exception itself implies an unusual conditions. Exceptions are anomalies that may occur  during execution of a program .exception are not errors(syntatical or logical) but they still cause the  program to misbehave. they are unusual conditions which are generally not excepted by the programmers to occur. an exception in this    sense is an indication  of a problem that occurs during a program' execution. the typical exception may include conditions like divide by zero , access to an array outside its range running out of memory etc.
for ex
#include <iostream.h>
int main()
{
int x, y;
cout<<"enter value of x& y\n";
cin>>x;
cin>>y;
cout<<"result ofx divided by y is:"<<x/y;
}
Exceptions are preferred in modern C++ for the following reasons:
  • An exception forces calling code to recognize an error condition and handle it. Unhandled exceptions stop program execution.
  • An exception jumps to the point in the call stack that can handle the error. Intermediate functions can let the exception propagate. They do not have to coordinate with other layers.
  • The exception stack-unwinding mechanism destroys all objects in scope according to well-defined rules after an exception is thrown.
  • An exception enables a clean separation between the code that detects the error and the code that handles the error.
The following simplified example shows the necessary syntax for throwing and catching exceptions in C++.
 
#include <stdexcept>
#include <limits>
#include <iostream>
 
using namespace std;
class MyClass
{
public:
   void MyFunc(char c)
   {
      if(c < numeric_limits<char>::max())
         throw invalid_argument("MyFunc argument too large.");
      //...
   }
};

int main()
{
   try
   {
      MyFunc(256); //cause an exception to throw
   }
 
   catch(invalid_argument& e)
   {
      cerr << e.what() << endl;
      return -1;
   }
   //...
   return 0;
}

  • aborting a program could leave a resource in a state in which other program would not be able to acquire the resources , hence the program would have a so-called "resource-leak".
  • exception should be thrown only within try block. an exception thrown outside a try block causes a call of terminate.
  • specifying comma   separated list of catch arguments is a syntax error
  • placing catch () before other catch blocks would prevent those blocks from ever being executed , catch() must be placed last in the list of handlers following a try lock
  • assuming that after exception is processed control return to the first statement after throw is a logic error
  • placing an empty throw  statement outside a catch handler; executing such a throw causes a call to terminate
  • user defined exception classes need not be derived from class exception. thus writing catch()exception) is not guaranteed to catch all exception a program may encounter.
exception handling is used in situation in which the system can recover from the error causing the exception. the recovery procedure is called an exception handler. the exception handling is typically used  when the error will be dealt by different part of the program from which detected the error
exception handling is  especially appropriate for situation in which the program will not be able to recover , but needs to provide orderly clean up shutdown gracefully.
  • use exception for errors that must be processed in a different scope fromn they occur. use other means of error handling for errors that will be processed in the scope in which they occur.
  • avoid using exception handling for purposes other than error handling because this can reduce program clarity.
  • although it is possible to use exception handling for purposes other than error handling , this can be reduce program performance
  • exception handling is generally implemented in compilers in such a manner that when an exception does not occur , little or no overheads is imposed by the presence of exception handling code.
ex
#include<iostream.h>
using.std::cont;
using.std::cin;
#include<new>
using std:: bad_alloc;
int main()
{
double*ptr[50];
try{for(int(i=1;i<50;i++)
{
ptr(i)=new double[500000];
cout<<"allocate 500000 double in ptr "<<i;
}
}
catch (bad_alloc.exception)
{cout<<"exception occured "<<exception.what()<<endI;
}
return 0;
}
b) what is data stream? Explain stream hierarchy in c++.
Q-5
a)What is template?Explain advantage of using template in C++? Write C++ program to explain function template and class template.
ans)templates are one of the most prominent example of reuse concept in action. it supports the idea of generic programming by providing facility for defining generic classes and functions. thus a template class provides a broad architecture which can be used to create a number of new classes. similarly , atemplate function can be used  to write various versions of the function..C++ templates enable you to define a family of functions or classes that can operate on different types of information.
  • Use templates in situations that result in duplication of the same code for multiple types.
    For example, you can use function templates to create a set of functions that apply the same algorithm to different data types.
  • You can also use class templates to develop a set of typesafe classes.
  • Templates are sometimes a better solution than C macros and void pointers,
    and they are especially useful when working with collections (one of the main uses for templates in MFC) and smart pointers (from MSDN).
  • A. Stepanov (the creator of STL) notes that some things that seem trivial using templates (such as equality operator, for example) are very difficult to implement with conventional OO techniques such as inheritance and polymorphism.
  • Because their parameters are known at compile time, template classes are more typesafe, and could be preferred over run-time resolved code structures (such as abstract classes). There are some modern techniques that can dramatically reduce code bloat when using templates. Note that these techniques are very complex either.
  • Often, the main reason to use templates in combination with STL – it can drastically reduce development time.
class template
template<classT>
class vector
{
T*v;//the vector is of type T
int size;
public:
vector(int m)
{
v=new[size=m];
for(inti=0;i<size;i++)
v[i]=0;
}
vector(t*a)
{for(int i=0;i<size;i++)
v[i]=a[i];
}
T operator*(vector&x)
{T sum=0;
for(inti=0;i<size;i++)
sum+=this->v[i]*x-v[i];
return(sum);
}
};
FUNCTION TEMPLATES
#include<iostream.h>
template<class T>
void bsort(T a[], int n)
{
for(int i=0;i<n-1;i<j;j--)
if(a[j]<a[j-1])
swap{a[j],a[j-1]);
}template<class X>
void swap(X &a,x&b)
{
xtemp=a;
a=b;
b=temp;
}
int main()
{
int x[5] = {10,50,30,60,40};
float y[5]={3.2,71.5,17.3,45.9,92.7};
bsort(x,5);
bsort(y,5);
cout<<"sorted X-array";
for(inti=0;i<5;i++)
cout<<x[i]<<"""";
cout<<endI;
cout<<"sorted  Y-array";
for(int j=0;j<5;j++)
cout<<y[j]<<"";
cout<<endI;
return(0);
};


(b)What is inheritance? Explain the different types of inheritance supported by C++?Explain whether constructors are inherited by derived class in C++ or not, write a program in support of your claim and show the output

   ans)   the new dimension of oop used a method called inheritance to modify a class to suit one's need  . inheritance means deriving new classes from the old ones . the old class is base class  or parent class or super class  and the cl;ass which derived from this base class is called as deriving class  or child class or sub class . deriving anew class from an existing one , allows   redifining a member function of base class and also  adding new members to the derived class and this is possible without having the source alsop. in other words the derived class not inherit all property  of the base class but also has some refinement  of its own. the base class remains unchanged in the process . in other words the derived class is a type of base class, but with more details added
DIFFERENT TYPES OF INHERITANCE-:
SINGLE INHERITANCE-:derivation of class from only one base class is called a single inheritance. class a is the base class and class b is the derived class . the following are the common steps o implement an inheritance. first declare a base class and second declare a derive class. the syntax of single inheritance is
class A
{
// member of a class A
};
classB:[public/private/protectected]A
{
//member of class B
};
MULTIPLE INHERITANCE-: derivation of aclass from several(two or more) base classes is called multiple inheritance.in multiple inheritance , derived class inherits  features from more than one parent(base class). in other way we can say that if a class is derived from more than one p is derived from more parent class than it is called multiple class
class A
{
// member of class A
};

class B
{
// member of class b

];
class c:[public/private/protected] A,[public/private/protected]B
{member of class c
};

MULTI_LEVEL INHERITANCE-:in multi level inheritance , the class inherits the feature of another derived class. if a class  C is derived from class B which in turn is derived from class A and so on. it is called multi level inheritance.
classA
{
//member function of class A
};
class B [public/private/protected]A
{
// member function of class B
};
class c:[public/private/protected]B
{
//member function of class c
};

The derived class need not have a constructor as long as base class has no- arguments constructor. however if any base class contains a constructor with arguments (one or more), it is necessary for the derived class to have a constructor and pass the arguments to the base class constructor. in inheritance , generally derived class objects are created instead of the base class. thus , it makes sense for the derived class to have a constructor and pass arguments to the constructor of the base class.  when an object of derive class is created , the constructor the constructor of the base class  is executed first and later on the constructor of derive class
  for ex-:
#include <iostream.h>
classA
{private:
int a;
protected:
int b;
public:
A(int i, intj)
{
a=i;
b=j;
cout<<"A initialized"<<endI;
}
void display_ab(void)
{
cout<<"\n the value of a is :"<<a;
cout<<"\n the value of b is :'<<b;
}
int get_a(void)
{
return a;
}};
class B
{private:
intc;
protected:
int d;
public:
B(int i, int j)
{
c==i;
d=j;
cout<<"\nbinitialized"<<endL;
}
void display_cd(void)
{
cout<<\n"the value of c is:'<<c
cout<<"\n the value of d is : "<<d;
}
int get_c(void)
{
return c;
}
};
class C:publicB,public A
{
int e,f,total;
public:
void c(intm,int n,int o, int p, int q, int r):A(m,n),B(o,p)
{
e=q;
f=r;
cout<<"\nc initialized ";
}
void sum(void)
{
total=get_aa()+b+get_c()+d+e+f;
}
void display(void)
{
cout<<"\n the value of e is:"<<e;
cout<<"\n the value of f is :"<<f;
cout<<\n the sum of a,b,c,d,e and f is:"<<total;
}
};
void main()
{
c objc(10,20,30,40,50,60);
objc.display_ab();
objc.display_cd();
objc.sum(?);
objc.display();
}
output is
B initialized
A initialized
C initialized
the value of a is :10
the value of b is:20
the value of c is:30
the value of dis:40
the value of e is :50
the vlaue of f is 60
the sum of a,b,c,d,e,fis :210


                                                                                                                                 
                                            < complete as soon as possible>
author

Author Name

Author Description!

Get Free Email Updates to your Inbox!

Entri Populer

www.CodeNirvana.in

infolink adds

Powered by Blogger.

Translate

Total Pageviews

Copyright © ignou solved assignments | Distributed By My Blogger Themes | Designed By Code Nirvana