MC0066_August_2010_OOPS using C++Completed

Embed Size (px)

Citation preview

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    1/33

    August 2010Master of Computer Application (MCA) Semester 2

    MC0066 OOPS using C++ 4 Credits

    (Book ID: B0681 & B0715) Assignment Set 1

    1. Describe the steps in compiling and executing a C++ program with programmaticillustration.

    Ans: There are three steps in executing a c++ program: Compiling, Linking and Running theprogram. The c++ programs have to be typed in a compiler. All the programs discussed in thebook will be compiled on turbo c++ compiler. The turbo c++ compiler comes with an editor totype and edit c++ program. After typing the program the file is saved with an extension .cpp.This is known as source code. The source code has to be converted to an object code whichis understandable by the machine. This process is known as compiling the program. You cancompile your program by selecting compile from compile menu or press Alt+f9. Aftercompiling a file with the same name as source code file but with extension .obj. is created.

    Second step is linking the program which creates an executable file .exe (filename same assource code) after linking the object code and the library files (cs.lib) required for the program.In a simple program, linking process may involve one object file and one library file. Howeverin a project, there may be several smaller programs. The object codes of these programs andthe library files are linked to create a single executable file. Third and the last step is runningthe executable file where the statements in the program will be executed one by one.

    The below example shows the entire process. When you execute the program, the compiler

    displays the output of the program and comes back to the program editor. To view the outputand wait for user to press any key to return to the editor, type getch() as the last statement inthe program. Getch() is an inbuilt predefined library function which inputs a character from theuser through standard input. However you should include another header file named conio.hto use this function. Conio.h contains the necessary declarations for using this function. Theinclude statement will be similar to iostream.h.

    Example.obj(Object code)

    Example.exe(Executable file)

    Cs.lib(Library file)

    Other objectcodes (if any)

    Example.cpp(Source code)

    Iostream.h(Header file)

    Compiling and Linking

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    2/33

    During compilation, if there are any errors that will be listing by the compiler. The errors maybe any one of the following

    Syntax error: This error occurs due to mistake in writing the syntax of a c++ statement orwrong use of reserved words, improper variable names, using variables without declarationetc. Examples are : missing semi colon or paranthesis, type integer for int datatype etc.Appropriate error message and the statement number will be displayed. You can see thestatement and make correction to the program file, save and recompile it.

    Logical error: This error occurs due to the flaw in the logic. This will not be identified by thecompiler. However it can be traced using the debug tool in the editor. First identify thevariable which you suspect creating the error and add them to watch list by selecting Debug->Watches->Add watch. Write the variable name in the watch expression. After adding allthe variables required to the watch list, go to the statement from where you want to

    observe. If you are not sure, you can go to the first statement of the program. Then selectDebug ->Toggle Breakpoint (or press ctrl + f8). A red line will appear on the statement.Then Run the program by selecting Ctrl + f9 or Run option from run menu. The executionwill halt at the statement where you had added the breakpoint. The watch variables andtheir values at that point of time will be displayed in the bottom in the watch window. PressF8 to execute the next statement till you reach the end of the program. In this way you canwatch closely the values in the watch variables after execution of each and every statementin the program. If you want to exit before execution of the last statement press Ctrl + Break.To remove the breakpoint in the program go to the statement where you have addedbreakpoint select Debug ->Toggle Breakpoint (or press ctrl + f8). Select Debug -> watch -

    >remove watches to remove the variables in the watch list. This tool helps in knowing thevalues taken by the variable at each and every step. You can compare the expected valuewith the actual value to identify the error.

    Linker error: This error occur when the files during linking are missing or mispelt

    Runtime error: This error occurs if the programs encounters division by zero, accessing anull pointer etc during execution of the program

    2. Describe the theory with programming examples the selection control statements in

    C++.Ans: There are basically two types of control statements in c++ which allows the programmer to

    modify the regular sequential execution of statements.They are selection and iterationstatements. The selection statements allow to choose a set of statements for executiondepending on a condition. If statement and switch statement are two statements which allowselection in c++. There is also an operator known as conditional operator which enablesselection.

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    3/33

    If statement

    Syntax : if (expression or condition)

    { statement 1;

    statement 2;

    }

    else

    { statement 3;

    statement 4;

    }

    The expression or condition is any expression built using relational operators which eitheryields true or false condition. If no relational operators are used for comparison, then theexpression will be evaluated and zero is taken as false and non zero value is taken as true. If

    the condition is true, statement1 and statement2 is executed otherwise statement 3 andstatement 4 is executed. Else part in the if statement is optional. If there is no else part, thenthe next statement after the if statement is exceuted, if the condition is false. If there is onlyone statement to be executed in the if part or in the else part, braces can be omitted.

    Following example program implements the if statement.

    // evenodd.cpp

    # include

    # include

    void main()

    {

    int num;

    cout

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    4/33

    as odd. We make use of the relational operator == to compare whether remainder is equal tozero or not.

    Nested If statementIf statement can be nested in another if statement to check multiple conditions.

    If (condition1)

    { if (condition 2)

    { statement1;

    Statement2;

    }

    else if (condition3)

    {statement3;

    }

    }

    else statement4;The flowchart of the above example is shown below

    Nested If Statement

    Multiple conditions can be checked using logical && operator(AND) and || operator (OR).

    If ((condition1) && (condition2))

    statement1;

    else

    statement2;

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    5/33

    In the above example statement1 will be executed if both the condition1 and condition2 aretrue and in all other cases statement2 will be executed.

    If ((condition1 || (condition2))

    statement1;

    else

    statement2;

    In the above example statement1 will be executed if either condition1 or condition2 are trueand even if both are true. Statement2 will be executed if both the conditions are false. Thefollowing program demonstrates the use of && operator and nested if statement.

    //Large.cpp

    # include

    void main()

    { int a,b,c;

    couta>>b>>c;

    if ((a>b) && (b>c))

    cout

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    6/33

    3. Given a RxC Matrix, A, i.e. R rows and C columns we define a Saddle-Point asSaddle_Pt (A(i,j)) = A(i,j) is the minimum of Row i and the maximum of Col j.

    e.g.1 2 34 5 67 8 9-- 7 is Saddle_Pt. at position (3,1)Write a program in C++ to check and print for saddle points in a matrix.

    Ans: Below is the programme code for saddle point.

    //Programm to find saddle point(s) in a matrix

    #include

    #include

    void main()

    {

    clrscr();

    int a[3][3],i,j,k,sp,minr,pos,flag=1;

    cout

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    7/33

    cout

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    8/33

    4. Describe and Demonstrate the concept of Pass by Value and Pass By Reference usingappropriate programming examples of your own

    Ans: Data can be passed to functions in two ways. One method is passing by value. The factfunction discussed in previous section implements passing by value. In this way of passing

    variables, a copy of the variable(main program) is created during function call with the namespecified in the function and initialized with the value in the original variable. All the operationsin the function is then performed on the function variable. The values in the variables declaredin the main program remains unchanged by the function operations.

    Another alternative to passing arguments is passing by reference. In passing by reference, nocopy of the variable is created. However, the variables in the main program are referred to bydifferent name in the function. Since no copy is created, when the values in the functionvariables are modified, the values in the variables in the main program are also modified.Passing by reference provides an easy mechanism for modifying the variables by functionsand also enables to return multiple variables.

    To pass arguments by reference, all the variable names in the argument list should beprefixed with & (ampersand) or address of operator during function declaration and definition.The following example shows the implementation of passing by reference.

    Function call is same for passing by reference.

    //passingbyreference.cpp

    # include

    int swap(int& m, int& n); // function declaration

    void main()

    {

    int a,b ;

    cout>a>>b;

    swap(a,b);

    cout

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    9/33

    void swap(int& m, int& n)

    { int temp;

    temp=m;

    m=n;

    n=temp;

    }

    In the above program, the variables a and b are passed by reference which implies that theywill be accessed directly. The variables are however will be referred as m and n in thefunction and are swapped. The result is that the function swaps the values in the originalvariables a and b.

    More than one user defined functions can have same name and perform different operations.This is a powerful feature of C++ and is known as function overloading. Every overloadedfunction should however have a different prototype. The following program implements aoverloaded function printline()

    //fnoverload.cpp

    # include

    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

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    10/33

    cout

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    11/33

    }

    void printline(char ch=*, int n=25);

    { for(int i=0;i

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    12/33

    for(int i=0;i

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    13/33

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    14/33

    The derived class can also add new class members and redefine existing base classmembers. In the above example, the two inherited members, a and b, of the derived class d,in addition to the derived class member c, are assigned values. If you redefine base classmembers in the derived class, you can still refer to the base class members by using the ::

    (scope resolution) operator. For example:

    #include

    using namespace std;

    class Base {

    public:

    char* name;

    void display() {

    cout

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    15/33

    You can manipulate a derived class object as if it were a base class object. You can use apointer or a reference to a derived class object in place of a pointer or reference to its baseclass. For example, you can pass a pointer or reference to a derived class object D to afunction expecting a pointer or reference to the base class of D. You do not need to use an

    explicit cast to achieve this; a standard conversion is performed. You can implicitly convert apointer to a derived class to point to an accessible unambiguous base class. You can alsoimplicitly convert a reference to a derived class to a reference to a base class.

    The following example demonstrates a standard conversion from a pointer to a derived classto a pointer to a base class:

    #include

    using namespace std;

    class Base {

    public:

    char* name;

    void display() {

    cout

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    16/33

    bptr->display();

    }

    Output:

    Base Class

    The statement Base* bptr = dptr converts a pointer of type Derived to a pointer of type Base.

    The reverse case is not allowed. You cannot implicitly convert a pointer or a reference to abase class object to a pointer or reference to a derived class. For example, the compiler willnot allow the following code if the classes Base and Class are defined as in the aboveexample:

    int main() {

    Base b;

    b.name = "Base class";

    Derived* dptr = &b;

    }

    The compiler will not allow the statement Derived* dptr = &b because the statement is tryingto implicitly convert a pointer of type Base to a pointer of type Derived.

    If a member of a derived class and a member of a base class have the same name, the baseclass member is hidden in the derived class. If a member of a derived class has the samename as a base class, the base class name is hidden in the derived class.

    Inheritance: Inheritance is a mechanism of reusing and extending existing classes withoutmodifying them, thus producing hierarchical relationships between them.

    Inheritance : It is almost like embedding an object into a class. Suppose that you declare anobject x of class A in the class definition of B. As a result, class B will have access to all thepublic data members and member functions of class A. However, in class B, you have toaccess the data members and member functions of class A through object x. The followingexample demonstrates this:

    #include

    using namespace std;

    class A {

    int data;

    public:

    void f(int arg) { data = arg; }

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    17/33

    int g() { return data; }

    };

    class B {

    public:

    A x;

    };

    int main() {

    B obj;

    obj.x.f(20);

    cout

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    18/33

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    19/33

    class A {

    public:

    int x;

    };

    class B : public A {

    public:

    int y;

    };

    class C : public B { };

    Class B is a direct base class of C. Class A is a direct base class of B. Class A is an indirectbase class of C. (Class C has x and y as its data members.)

    Polymorphic functions are functions that can be applied to objects of more than one type. InC++, polymorphic functions are implemented in two ways:

    Overloaded functions are statically bound at compile time.

    C++ provides virtual functions. A virtual function is a function that can be called for a numberof different user-defined types that are related through derivation. Virtual functions are bounddynamically at run time. They are described in more detail a little further in the chapter.

    6. Describe the Friend functions and friend classes with programming examples.

    Ans: Friend classes in C++ give us access to non-member functions or other classes. By using thefriend keyword, a class can grant access to non-member functions or to another class. Thesefriend functions and friend classes are permitted to access private and protected classmembers. There are places where friends can lead to more intuitive code, and are oftenneeded to correctly implement operator overloading.

    If encountering friend functions for the first time, you might feel slightly uneasy since theyseem to violate encapsulation. This feeling may stem from the fact that a friend function is notstrictly a member of the class. By thinking of a friend function as part of the classs publicinterface, you can get a better understanding of how friends work. From a design perspective,friends can be treated in a similar way to public member functions. The concept of a classinterface can be extended from public members to include friend functions and friend classes.Put another way: Friend functions do not break encapsulation; instead they naturally extendthe encapsulation barrier.

    Friend Functions: Friend functions can be declared anywhere within a class declaration, butit is common practice to list friends at the beginning of the class. The public and protected

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    20/33

    keywords do not apply to friend functions, as the class has no control over the scope offriends.

    If we want to declare an external function as friend of a class, thus allowing this function tohave access to the private and protected members of this class, we do it by declaring aprototype of this external function within the class, and preceding it with the keyword friend:

    // friend functions

    #include

    using namespace std;

    class CRectangle

    {

    int width, height;

    public:

    void set_values (int, int);

    int area () {return (width * height);}

    friend CRectangle duplicate (CRectangle);

    };

    void CRectangle::set_values (int a, int b) {

    width = a;

    height = b;

    }

    CRectangle duplicate (CRectangle rectparam)

    {

    CRectangle rectres;

    rectres.width = rectparam.width*2;rectres.height = rectparam.height*2;

    return (rectres);

    }

    int main ()

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    21/33

    {

    CRectangle rect, rectb;

    rect.set_values (2,3);

    rectb = duplicate (rect);

    cout

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    22/33

    public:

    CPoint(const double x, const double y) :

    m_x(x),

    m_y(y) { }

    ~CPoint(void) { }

    //

    };

    Since the collection class is a friend of CPoint, it has access to the internal data of any point

    object. This is useful when individual elements of the collection need to be manipulated. Forexample, a set method of the CPointCollection class could set all CPoint elements to aparticular value (vector is a STL container which is discussed in detail in Chapter 8):

    class CPointCollection

    {

    private:

    vector m_vecPoints;

    public:CPointCollection(const int nSize) :

    m_vecPoints(nSize) { }

    ~CPointCollection(void);

    void set(const double x, const double y);

    //

    };

    The set member can iterate over the collection and reset each point:

    void CPointCollection::set(const double x, const double y) {

    // Get the number of elements in the collection.

    const int nElements = m_vecPoints.size();

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    23/33

    // Set each element.

    for(int i=0; i

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    24/33

    Stream Classes in C++: As shown in the fig. 9.1 all stream classes have been inherited fromthe base class ios. It contains many constants and member functions common to all kind ofinput and output. The class istream is derived from ios class which contains all the necessaryfunctions for handling input. Some of the functions such as get(), getline(), read and

    overloaded extraction (>>) operators are defined in istream class. While ostream class whichis also derived from ios class is dedicated for output related functions of all kinds and containsfunctions such as put() and write and overloaded insertion operator (

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    25/33

    also includes iostream.h, so the programs using fstream.h need not explicitly includeiostream.h.

    Character and String input and output to files: Let us see some programs that writes andreads characters and strings to text file. To write any data to a file, you should create anobject of ofstream class. The function put() is used with the object to write to the file. Ithowever writes one character at a time. The syntax of put() function is :

    objectname.put(character variable).

    The following program shows the use of put() function:

    #include

    # include

    void main()

    {

    ofstream outfile(test.txt);

    char str[ ]=hello world;

    for (int j=0;j

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    26/33

    To read data from any file, you should create an object of ifstream class. The function get()and getline() is used with the object to read the file. The function get() reads one character ata time. The syntax of get() function is :

    objectname.get(character variable)

    where object is an object of the ifstream class and the character read is stored in the variable.

    The following program reads the contents of a text file character by character and prints onthe screen.

    #include

    #include

    void main()

    {

    ifstream infile("test.txt");

    char ch;

    clrscr();

    while (infile) // infile becomes 0 when eof condition is reached

    {infile.get(ch);

    cout

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    27/33

    {infile.getline(buffer,80);

    cout >) is overloaded in the class istream class (ifstream is derivedfrom istream), it can be used along with the ifstream object to read text. However it reads oneword at a time. The following program shows that

    #include

    #include

    void main()

    {

    ifstream infile("test.txt");

    char buffer[25];clrscr();

    while (infile) //infile becomes 0 when eof condition is reached

    {infile>>buffer;

    cout

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    28/33

    while (infile) //infile becomes 0 when eof condition is reached

    {infile>>buffer;

    cout

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    29/33

    Consider the following:

    //B.H

    template

    class b {

    public:

    b();

    ~b();

    };

    //B.CPP

    #include "B.H"

    template

    b::b() {

    }

    template

    b::~b() {

    }

    //MAIN.CPP

    #include "B.H"

    void main() {

    b bi;

    b bf;

    }

    When compiling B.cpp, the compiler has both the declarations and the definitions available. Atthis point the compiler does not need to generate any definitions for template classes, sincethere are no instantiations. When the compiler compiles main.cpp, there are twoinstantiations: template class B and B. At this point the compiler has thedeclarations but no definitions.

    While implementing class template member functions, the definitions are prefixed by thekeyword template. Here is the complete implementation of class template Stack:

    //stack.h#pragma once

    template

    class Stack {

    public:

    Stack(int = 10);

    ~Stack() { delete [] stackPtr; }

    int push(const T&);

    int pop(T&); // pop an element off the stack

    int isEmpty()const { return top == -1; }

    int isFull() const { return top == size 1; }

    private:

    int size; // Number of elements on Stack

    int top;

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    30/33

    T* stackPtr;

    };

    //constructor with the default size 10

    template

    Stack::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

    int Stack::push(const T& item) {

    if (!isFull())

    {

    stackPtr[++top] = item;

    return 1; // push successful

    }

    return 0; // push unsuccessful

    }

    // pop an element off the Stack

    template

    int Stack::pop(T& popValue) {

    if (!isEmpty())

    {

    popValue = stackPtr[top--];

    return 1; // pop successful

    }

    return 0; // pop unsuccessful

    }

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    31/33

    Using a class template: Using a class template is easy. Create the required classes byplugging in the actual type for the type parameters. This process is commonly known as"Instantiating a class". Here is a sample driver class that uses the Stack class template.

    #include

    #include "stack.h"

    using namespace std;

    void main() {

    typedef Stack FloatStack;

    typedef Stack IntStack;

    FloatStack fs(5);

    float f = 1.1;

    cout

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    32/33

    while (is.pop(i))

    cout

  • 8/7/2019 MC0066_August_2010_OOPS using C++Completed

    33/33

    If the template definition changes, simply change the typedef definition. For example,currently the definition of template class vector requires a second parameter.

    typedef vector INTVECTOR;

    INTVECTOR vi1;

    In a future version, the second parameter may not be required, for example,

    typedef vector INTVECTOR;

    INTVECTOR vi1;

    Imagine how many changes would be required if there was no typedef!