bcsl-031 solved assignment 2013-14

Upload: babji-babu

Post on 10-Feb-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/22/2019 BCSL-031 Solved Assignment 2013-14

    1/13

    Question 1:

    (a) Explain why Object Oriented Programming approach is better than Structured ProgrammingApproach. (5 Marks)

    Ans :- For the most part, web developers the world over have to contend with programming their back-end applications using either structured or object-oriented programming. So what exactlydo those terms mean? Keep reading to find out as I compare structured and object oriented

    programming in this article.

    Definition of Structured Programming

    Structured programming can be defined as a Software application programming technique that follows a top down design approach with block oriented structures.This style of programming is characterized by the programmers tendency to divide his programsource code into logically structured blocks which would normally consist of conditionalstatements, loops and logic blocks. This style of programming has the implementation of thesource code being processed in the order in which bits of the code have been typed in.

    Definition of Object-Oriented Programming

    Object-oriented programming can be defined in simplest terms assoftware application programming where there is an interaction between self-contained mini-

    programs or objects within the main program. In other terms, object-oriented programming can be known as the process of using several classes to represent different areas of functionality or data objects within your software application. These data objects have data fields and functionsthat act on the data fields. The hold three main characteristics which are encapsulation,inheritance, and polymorphism. Examples of objects would include windows, menus, text inputs,icons, etc. There must be procedures to manipulate them.

  • 7/22/2019 BCSL-031 Solved Assignment 2013-14

    2/13

    (b) Write a simple C++ program to explain the basic structure of C++ programming. (5 Marks)Ans :- Probably the best way to start learning a programming language is by writing a program.Therefore, here is our first program:

    1 // my first program in C++ 23 #include 4 using namespace std;56 int main ()7 {8 cout

  • 7/22/2019 BCSL-031 Solved Assignment 2013-14

    3/13

    int main ()This line corresponds to the beginning of the definition of the main function. The mainfunction is the point by where all C++ programs start their execution, independently of itslocation within the source code. It does not matter whether there are other functions withother names defined before or after it - the instructions contained within this function'sdefinition will always be the first ones to be executed in any C++ program. For that samereason, it is essential that all C++ programs have a main function.

    The word main is followed in the code by a pair of parentheses ( () ). That is because it isa function declaration: In C++, what differentiates a function declaration from other typesof expressions are these parentheses that follow its name. Optionally, these parenthesesmay enclose a list of parameters within them.

    Right after these parentheses we can find the body of the main function enclosed in braces ( {} ). What is contained within these braces is what the function does when it isexecuted.

    cout

  • 7/22/2019 BCSL-031 Solved Assignment 2013-14

    4/13

    %

    ++

    The sizeof operator can be used to get the size of classes, structures, unions and any other user defined data type.

    The syntax of using sizeof is as follows:

    sizeof (data type)

    Where data type is the desired data type including classes, structures, unions and any other user defined data type.

    B ) Logical Operators :- An operator is a symbol that tells the compiler to perform specificmathematical or logical manipulations. C++ is rich in built-in operators and provides thefollowing types of operators:

    Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Misc Operators

    This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

    Arithmetic Operators:

    There are following arithmetic operators supported by C++ language:

    Assume variable A holds 10 and variable B holds 20, then:

    Show Examples

    Operator Description Example + Adds two operands A + B will give 30- Subtracts second operand from the first A - B will give -10* Multiplies both operands A * B will give 200/ Divides numerator by de-numerator B / A will give 2

    Modulus Operator and remainder of after an integer division B % A will give 0 Increment operator , increases integer value

    by one A++ will give 11-- Decrement operator , decreases integer A-- will give 9

  • 7/22/2019 BCSL-031 Solved Assignment 2013-14

    5/13

    value by one

    C ) Scope resolution operator :- The :: (scope resolution) operator is used to qualify hidden

    names so that you can still use them. You can use the unary scope operator if a namespace scopeor global scope name is hidden by an explicit declaration of the same name in a block or class.For example:

    int count = 0;

    int main(void) {int count = 0;::count = 1; // set global count to 1count = 2; // set local count to 2return 0;

    }

    The declaration of count declared in the main() function hides the integer named countdeclared in global namespace scope. The statement ::count = 1 accesses the variable namedcount declared in global namespace scope.

    You can also use the class scope operator to qualify class names or class member names. If aclass member name is hidden, you can use it by qualifying it with its class name and the classscope operator.

    In the following example, the declaration of the variable X hides the class type X, but you can stilluse the static class member count by qualifying it with the class type X and the scope resolution

    operator.#include using namespace std;

    class X{public:

    static int count;};int X::count = 10; // define static data member

    int main (){

    int X = 0; // hides class type Xcout

  • 7/22/2019 BCSL-031 Solved Assignment 2013-14

    6/13

    (a) Define the class Book with all the basic attributes such as title, author, publisher, price etc.Define the default constructor, member functions display_data() for displaying the Book details. Use appropriate access control specifiers in this program. (8 Marks)

    Ans :- class Book{ public :

    enum Genre{fiction = 0, nonfiction, periodical, biography, children};

    class Invalid{//...

    };

    Book( int isbn, string author, string title, string copyright, Genregenre, string status)

    Book();

    int isbn(); const { return isbn;}

    string author(); const { return author;}string title(); const { return title;}string copyright(); const { return copyright;}Genre genre(); const { return genre;}string status(); const { return status;}

    private :int isbn;string author;string title;string copyright;Genre genre;string status;

    };

    (b) Explain the following terms in the context of object oriented programming. Also explain howthese concepts are implemented in C++ by giving an example program for each.

    (8 Marks) (a) Abstraction :- Data abstraction refers to, providing only essential information

    to the outside word and hiding their background details, i.e., to represent theneeded information in program without presenting the details.

    (b) Encapsulation :- Encapsulation is the process of combining data andfunctions into a single unit called class. Using the method of encapsulation,

    the programmer cannot directly access the data. Data is only accessiblethrough the functions existing inside the class. Data encapsulation led to theimportant concept of data hiding. Data hiding is the implementation detailsof a class that are hidden from the user. The concept of restricted access led

    programmers to write specialized functions or methods for performing theoperations on hidden members of the class. Attention must be paid to ensurethat the class is designed properly.

  • 7/22/2019 BCSL-031 Solved Assignment 2013-14

    7/13

    (c) Operator Overloading :- using the assignment operator is fairlystraightforward, correctly implementing an overloaded assignment operator can be a little more tricky than you might anticipate. There are two primaryreasons for this. First, there are some cases where the assignment operator isnt called when you might expect it to be. Second, there are some issues in

    dealing with dynamically allocated memory (which we will cover in the nextlesson).

    Static Member :- C++ introduces two new uses for the static keyword when applied to classes:static member variables, and static member classes. Before we go into the static keyword asapplied to member variables, first consider the following class:

    12 class Something3 {4 private:int m_nValue;5 public:6 Something() { m_nValue = 0; }7 };89 int main()10{ 111213} 14

    Something cFirst;Something cSecond;return 0;

    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 withtwo copies of m_nValue one inside cFirst, and one inside cSecond. cFirst->m_nValue isdifferent than cSecond->m_nValue.

    Question 3:

    (a) What is polymorphism? What are different forms of polymorphism? Explainimplementation of polymorphism with the help of a C++ program. (8 Marks)

    Ans :- The word polymorphism means having many forms. Typically, polymorphism occurswhen there is a hierarchy of classes and they are related by inheritance.

  • 7/22/2019 BCSL-031 Solved Assignment 2013-14

    8/13

    C++ polymorphism means that a call to a member function will cause a different function to beexecuted depending on the type of object that invokes the function.

    #include using namespace std;

    class Shape {protected:

    int width, height;public:

    Shape( int a=0, int b=0){

    width = a;height = b;

    }int area(){

    cout

  • 7/22/2019 BCSL-031 Solved Assignment 2013-14

    9/13

    // store the address of Triangleshape = &tri;// call triangle area. shape->area();

    return 0;}

    (b) What is friend function? How it is implemented in C++? Explain advantages of using friendfunction with the help of an example. ( 8 Marks)

    Ans :- A friend function of a class is defined outside that class' scope but it has the right toaccess all private and protected members of the class. Even though the prototypes for friendfunctions appear in the class definition, friends are not member functions.

    A friend can be a function, function template, or member function, or a class or class template, inwhich case the entire class and all of its members are friends.

    To declare a function as a friend of a class, precede the function prototype in the class definitionwith keyword friend as follows:

    class Box{

    double width;public:

    double length;friend void printWidth( Box box );void setWidth( double wid );

    };

    Question 4 :

    (a) Explain the following functions for manipulating file pointers, with the help of example program: (8 Marks)

    seekg() :- Internally, the function accesses the input sequence by first constructing asentry object (with noskipws set to true ). Then (if good ), it calls either pubseekpos (1) or pubseekoff (2) on its associated stream buffer object (if any). Finally, itdestroys the sentry object before returning.

    seekp() :- This function simply copies a block of data, without checking its contentsnor appending a null character at the end.

    If the input sequence runs out of characters to extract (i.e., the end-of-file is reached) before n characters have been successfully read, the array pointed by s contains all the

  • 7/22/2019 BCSL-031 Solved Assignment 2013-14

    10/13

    characters read until that point, and both the eofbit and failbit flags are set for thestream.

    tellg() :- the function accesses the input sequence by first constructing a sentry object

    (with noskipws set to true ) without evaluating it. Then, if member fail returns true ,the function returns -1 .Otherwise, returns rdbuf ()-> pubseekoff (0,cur,in) . Finally, it destroys the sentryobject before returning.

    tellp() :- Returns the position of the current character in the output stream.

    (b) What is an exception? How an exception is different from an error? Explain howexceptions are handled in C++, with the help of an example program. (8 Marks)

    Ans :- Exception handling is a mechanism that separates code that detects and handles

    exceptional circumstances from the rest of your program. Note that an exceptional circumstanceis not necessarily an error.

    When a function detects an exceptional situation, you represent this with an object. This object iscalled an exception object . In order to deal with the exceptional situation you throw theexception . This passes control, as well as the exception, to a designated block of code in a director indirect caller of the function that threw the exception. This block of code is called a handler .In a handler, you specify the types of exceptions that it may process. The C++ run time, together with the generated code, will pass control to the first appropriate handler that is able to processthe exception thrown. When this happens, an exception is caught . A handler may rethrow anexception so it can be caught by another handler.

    Question 5:

    (a ) What is template? Write appropriate statements to create a template class for Stack datastructure in C++. (8 Marks)

    Ans :- Templates are the foundation of generic programming, which involves writing code in away that is independent of any particular type.

    A template is a blueprint or formula for creating a generic class or a function. The library

    containers like iterators and algorithms are examples of generic programming and have beendeveloped using template concept.

    There is a single definition of each container, such as vector , but we can define many differentkinds of vectors for example, vector or vector .

    #include #include

  • 7/22/2019 BCSL-031 Solved Assignment 2013-14

    11/13

    #include #include #include

    using namespace std;

    template class Stack {

    private:vector elems; // elements

    public:void push(T const&); // push elementvoid pop(); // pop elementT top() const; // return top elementbool empty() const{ // return true if empty.

    return elems.empty();}

    };

    template void Stack::push (T const& elem){

    // append copy of passed elementelems.push_back(elem);

    }

    template void Stack::pop (){

    if (elems.empty()) {throw out_of_range("Stack::pop(): empty stack");

    }// remove last element

    elems.pop_back();}

    template T Stack::top () const{

    if (elems.empty()) {throw out_of_range("Stack::top(): empty stack");

    }// return copy of last element

    return elems.back();}

    int main(){

    try {Stack intStack; // stack of intsStack stringStack; // stack of strings

    // manipulate int stackintStack.push(7);cout

  • 7/22/2019 BCSL-031 Solved Assignment 2013-14

    12/13

    // manipulate string stackstringStack.push("hello");cout

  • 7/22/2019 BCSL-031 Solved Assignment 2013-14

    13/13

    protected:int width;int height;

    };

    // Derived classclass Rectangle: public Shape{

    public:int getArea(){

    return (width * height);}

    };

    int main(void){

    Rectangle Rect;

    Rect.setWidth(5);

    Rect.setHeight(7);

    // Print the area of the object.cout