cs2203 oops 16marks

Upload: ramraj-santhanam

Post on 03-Jun-2018

228 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 Cs2203 Oops 16marks

    1/46

  • 8/12/2019 Cs2203 Oops 16marks

    2/46

    2

    Abstraction refers to the act or representing essential features without

    including the background details. The attributes are sometimes called as data

    members and functions that operating on that data is called member

    function. A class using the data abstraction concept is known as Abstract

    Data Type (ADT).

    Inheritance:Inheritance is the process by which objects acquiring the properties

    of the object of another class. The important property of inheritance is

    Reusability. Also define as Inheritance is a mechanism of deriving a new

    class from an old class. Here we say new class as derived Class and an Old

    Class as Base Class.

    Polymorphism:It is a Greek term, means ability to take more than one form. An

    operation may exhibit different behaviors in different instances. There are

    two types of polymorphism. They are, operator overloading and functionoverloading. The process of making an operator to exhibit different behavior

    in different instances is operator overloading. The process of making a

    function to exhibit different behavior in different instances is function

    overloading.

    Dynamic Binding:Binding refers to the linking of the procedure call to the code to be

    executed in response to the call. Dynamic (Late) Binding means that the

    code associated with the given procedure call isnt known until the time or

    the call at runtime.

    Message Passing:Message Passing is the process of communication between the objects.

    Creating classes that defines objects and their behavior. Creating object from class. Establishing communication among objects.

    Message for an object is a request for execution of a procedure and

    therefore it will invoke a function. Message passing involves specifying the

    name of the object, name of the function and information to be sent.

    Example: Employee. Salary (name);

    Where employee is the object, salary is the function and the name is the

    information.

    2. Write a C++ program using inline functionInline function is expanded in line when it is invoked. The compiler replaces the

    function call with the corresponding function code.

    Syntax:

    1. datatype function(parameters) { statements; }2. inline datatype class::function (parameters) { statements; }

  • 8/12/2019 Cs2203 Oops 16marks

    3/46

    3

    The first syntax example declares an inline function by default. The syntax must

    occur within a class definition.

    The second syntax example declares an inline function explicitly. Such

    definitions do not have to fall within the class definition.

    Samples:

    /* First example: Implicit inline statement */

    int num; // global num

    class cat

    {

    public:

    char* func(void) { return num; }

    char* num;

    }

    /* Second example: Explicit inline statement */

    inline char* cat::func(void) { return num; }

    Program to defi ne fun ction cube ( ) as in li ne for calculatin g cube:

    void main ( )

    {

    clrscr ( );

    int cube (int);int j, k, v = 5;

    j = cube (3);

    k = cube (v);

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    4/46

    4

    int sqr (int);

    float sqr (float);

    int main ( )

    {

    int a = 15;

    float b = 2.5;cout

  • 8/12/2019 Cs2203 Oops 16marks

    5/46

    5

    public:

    void get()

    {

    couta;

    }

    void show()

    { cout

  • 8/12/2019 Cs2203 Oops 16marks

    6/46

    6

    Output:

    Enter the value for a: 3

    a = 3

    Enter the value for b: 5

    b = 5

    Nested Class:

    Inheriting one class into other class. In the nested class the member objectare created using their respective constructors and then the other ordinary

    members are created.

    All objects of one class will contain the objects of another class. This kindof relation is called containership or nesting.

    Nested object can be created by two stages. First the member object iscreated using their respective constructors and then the other ordinary

    members are created.

    Example:

    Class gamma

    {

    alpha a; // a is an object of alpha class

    beta b; // b is an object of beta class

    public:

    gamma (arglist) : a (arglist1), b (arglist2)

    {

    // Constructor

    }

    };

    gamma (int x, int y, int z) : a (x), b (x,z)

    5. Explain Friend Function and its with suitable example and also itscharacteristics.

    A function that is declared with a keyword friend is known as friend function. Afunction can be declared as a friend in any number of classes.

    Friend function must be preceded with a keyword friend. The function defined elsewhere in the program like normal C++ function.

    Function definition doesnt use either keyword friend or scope resolution

    operator.

    Friend function although not a member function, it has full rights to access theprivate members of a class

  • 8/12/2019 Cs2203 Oops 16marks

    7/46

    7

    Declaration:

    Class class-name

    {

    Public:

    ..Friend void xyz (void);

    };

    Example:

    #include

    class sample

    {

    int a, b;

    public:

    void setvalue( )

    {

    a=25; b=40;

    }

    friend float mean (sample s);

    };

    float mean (sample s)

    {

    return float (s.a + s.b) / 2.0;

    }

    int main ( )

    {

    sample x;

    x.setvalue ( );

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    8/46

    8

    1. Explain Constructor with suitable example. Discuss any two types ofConstructors with suitable example.

    A constructor is a special member function whose task is to initialize the

    objects of its class. It is special because its name is same as class name. Theconstructor is invoked whenever an object of its associated class is created. It is

    called constructor because it constructs the values of data members of the class

    Example:

    #include

    class num

    {

    private:

    int a, b, c;

    public:num (void); // Declaration of the Constructor

    void show ( )

    {

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    9/46

    9

    2. By calling the constructor implicitlyeg: Integer int1(10,10);

    Example:

    #include

    class num

    {

    private:

    int a, b, c;

    public:

    num (int m, int j, int k); // Parameterized Constructor

    void show ( )

    {

    cout cout

  • 8/12/2019 Cs2203 Oops 16marks

    10/46

    10

    public:

    num ( ) { } // Constructor without arguments

    num (int k) { n = k; } // Parameterized Constructor

    num (num &j) { n = j.n; } // Copy Constructor

    void show ( ) { cout

  • 8/12/2019 Cs2203 Oops 16marks

    11/46

    11

    {

    int x;

    int y;

    int z;

    public: void getdata (int a, int b, int c);

    void display (void);

    void operator( );

    };

    void space :: getdata (int a, int b, int c)

    {

    x = a; y = b; z = c;

    }

    void space :: display (void)

    {

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    12/46

    12

    Example:

    class space

    { int x;

    int y;

    int z;

    public:

    void getdata (int a, int b, int c);

    void display (void);

    friend void operator( space &s);

    };

    void space :: getdata (int a, int b, int c)

    {

    x = a; y = b; z = c;

    }

    void space :: display (void)

    {

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    13/46

    13

    For Basic Type,

    int m;

    float x = 3.14;

    m = x;Convert x to an int before its value assigned to m. fractional part is truncated.

    For User Defined DT conversions can be done as,

    a) Conversion from Basic Type to Class Type,b) Conversion from Class Type to Basic Type,c) Conversion from Class Type to Class Type.

    Basic to Class Type Conversion:

    Also can be called as type casting. It can be easily carried out by the compilerautomatically.

    In this type the Left hand operand of = sign is always class type and Right HandOperand is always basic type.

    Program to defi ne constructor with no arguments and with fl oat arguments:

    class data

    {

    int x;

    float f;

    public:

    data (){ x = 0; f = 0; }

    data (float m)

    { x = 2; f = m; }

    void show ()

    {

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    14/46

    14

    X = 2 f = 1

    X = 2 f = 1

    X = 2 f = 2.5

    X = 2 f = 2.5

    Class to Basic Type Conversion:

    In this the constructor has no effect. So the type casting can be used by which theuser cans explicitly telling to the compiler for conversions.

    These instructions are written in memory functions. The compiler first searches for the operator keyword followed by DT. If it is not

    found then the compiler applies the conversion function.

    In this type the Left hand operand of = sign is always basic type and Right HandOperand is always class type.

    The syntax is,

    operator type name (){ function statements; }

    Example:operator double { }

    To convert class type to basic type following conditions should be satisfied,

    Conversion function doesnt have any arguments. It should be a class member function.

    Example:

    class data

    {

    int x;

    float f;

    public:

    data ()

    { x = 0; f = 0; }

    operator int ()

    { return x; }

    operator float ()

    { return f; }data ( float m)

    { x = 2; f = m; }

    void show ()

    {

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    15/46

    15

    clrscr();

    int j; float f;

    data a;

    a = 5.5; // a is a class object & j is int basic DT

    j = a; //operator int is executed

    f = a; //operator float is executedcout

  • 8/12/2019 Cs2203 Oops 16marks

    16/46

    16

    public:

    void operator = (minutes x)

    void show ()

    {

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    17/46

    17

    If the templates associated with classes it is called as class templates. For eg, if the user

    creates a class templates for a class Array it would enable the user to create arrays of various

    types like int and float.

    Syntax:

    template class

    class name _of_class

    {

    // class data member and function

    }

    The statement template class tells the compiler that the following class declaration

    can use the template data type. T is the template variable. Both template and class are

    keywords. < > is used to declare the template variable that can be used inside the class to

    define the template variable.

    If the user declares more than one variable then it can be separated by comma. Template cant be declared inside a class or function. They must be global not

    a local.

    T k;Where k is the object for the template variable T

    In NonTemplate function the source code can be increased in size because ofredefining the function separately for each data type.

    To avoid the declaration and defining of constructor for different data types the templatescan be used.

    In Templates, different values are passed using constructor but for all data types sametemplate function is used.Function Templates:

    The difference between normal function and member function is that the normal

    functions are defined outside the class. They are not members of any class and hence it can be

    invoked directly without using dot operator. The member functions are the class members.

    They can be invoked using objects of the class which belongs to it.

    Syntax:

    Template class

    Function_name ( )

    { // Code }

  • 8/12/2019 Cs2203 Oops 16marks

    18/46

    18

    Progr

    am to

    define

    normal

    templ

    ate

    functi

    on:

    Templ

    ate

    voidshow

    (T x)

    {

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    19/46

    19

    Developing an error free program is the main objective and intention of theprogrammer.

    For that the programmer can manually check the errors. The errors are either alogical or syntax error.

    Logical Error is due to the poor understandings of the program and the Syntax Erroris due to the lack of understanding of programming language.

    To resolve this C++ have the special feature called Exception Handling whichreduces the errors made by the developer.

    An Exception is abnormal termination of the program which is executed at runtimeor it may be called at runtime.

    The Exception contains warning messages like invalid argument, insufficientmemory, division by zero and so on.

    Principles:

    The goal is to create a Routine that detects and sends an exceptional condition in orderto execute suitable action.

    The Routine having responsibilities like, Find the Problem (Hit the Exception), Inform that an error has occurred (Throw), Receive the error information (Catch), Take corrective Actions (Handling the Exception).

    An Exception is an object. It is sent from the part of the program where an error occursto that part the program which is going to control the error.

    There are two types of exceptions, Synchronous Exceptions, Asynchronous Exceptions.

    Synchronous Exception: An error such as out of range or overflow belongs to it.

    Asynchronous Exception: Errors that are occurred by the events beyond the control of program such as

    keyboard interrupts are belong to this exception.

    The Error Handling code consists of two segments, one to detect errors and to throw theexceptions and other to catch the exceptions and to take appropriate actions.

    Mechanism:

    C++ provides three mechanisms,

    1)The Keyword Try is used at the starting of the exception,2)The Keyword Throw block is present inside the Try block, Immediately after Try,

    Catch block is present.

    3)If an exception found then the Throw statement inside the Try block throws anexception for a Catch block that an error has occurred.

  • 8/12/2019 Cs2203 Oops 16marks

    20/46

    20

    Flow Diagram:

    Try Block

    Find Errors and Throws an Exception

    Throw Block

    Throws Exception

    Program to Throw an Exception:

    int main ()

    {

    int x, y, j;

    cout x>>y;j = x > y ? 0:1;

    try

    {

    if (j ==0)

    { cout

  • 8/12/2019 Cs2203 Oops 16marks

    21/46

    21

    3. Explain the Exception Specification with example in detail. This can be used to throw only the specified exception using a throw list

    condition.

    The Format for this is,data-type function_name (parameter list) throw (data type list)

    {

    statements1;

    statements2;

    }The data type list indicates the type of exceptions to be thrown.

    If the user wants to deny a function from throwing exception then the user candeclare data type list as void.

    throw (); // void or vacant list

    Program to restr ict a function to throw only specif ied type of exceptions:

    void check (int k) throw (int, double)

    {

    if (k == 1) throw k;

    else if (k ==2) throw k;

    else if (k ==-2) throw 1.0;

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    22/46

    22

    Output:

    K ==1

    Caught a Char Exception

    End of main

    4. Explain the Uncaught Exception with example in detail.C++ having two functions to control uncaught exceptions.

    a. Terminate () Functionb. Set_terminate () Function

    Terminate () Function:

    If the exception handler is not defined while the exception is thrown then the

    Terminate () function is invoked. Implicitly the abort () function is invoked.

    Program to catch uncaught exceptions:

    class one { };

    class two { };

    void main ()

    {

    try

    {

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    23/46

    23

    void main ()

    {

    set_terminate (skip);

    try

    {cout

  • 8/12/2019 Cs2203 Oops 16marks

    24/46

    24

    show (50);

    show (50.25);

    return 0;

    }

    Output:

    Template Variable C = C

    Integer Variable F = 50

    Template Variable C = 50.25

    Unit - IV

    1.What are the different forms of Inheritance? Explain Multiple Inheritances.The new classes are created from the existing one is known as Inheritance. The

    important property of inheritance is Reusability. The properties of existing class are extended

    to new class. New class are called as derived class and the existing class is known as base class

    Types (or) Forms of Inheritance:

    Single I nheri tance:

    This contains one base class as well as one derived class.

  • 8/12/2019 Cs2203 Oops 16marks

    25/46

    25

    Multi ple Inheri tances:

    This contains two base classes and one derived class.

    Multi level I nheritance:

    This contains one base class more than one derived classes.

    H ierarchal I nheritance:

    This contains one base class more than one derived classes arranged in a level order.

    Hybri d or M ulti - path I nheri tance:

    A

    B

    B

    C

    A

    C

    A

    B

    A

    B C D

  • 8/12/2019 Cs2203 Oops 16marks

    26/46

    26

    This contains one base class more than one derived classes and from the

    derived classes another derivation can be done to get sub derived class. This is the

    combination of Multiple, Multilevel and Hierarchal Inheritance.

    Multiple Inheritances:

    This contains two base classes and one derived class.

    Program to derive a class from Mul tiple Base Classes:

    Class A {public: int a; }; // Class A declaration

    Class B {public: int b; }; // Class B declaration

    Class C {public: int c; }; // Class C declaration

    Class D {public: int d; }; // Class D declaration

    Class E : public A, public B, public C, public D // Class E

    {

    public:

    int e;

    void getdata( )

    {

    couta>>b>>c>>d>>e;

    }void putdata( )

    {

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    27/46

    27

    Output:

    Enter the values of a, b, c, d and e: 1 2 3 4 5

    a=1 b=2 c=3 d=4 e=5

    2.Explain in detail about Virtual Base Class and Abstract Class with example.Virtual Base Class:

    In Multipath Inheritance more than one derived classes try to access the base class

    member then the error occurs.

    To resolve this ambiguity C++ provides the keyword VIRTUAL. When the class is declared as virtual then the compiler takes necessary precaution to

    avoid the duplication of base class.

    After virtual, the base class can be accessed by any number of derived classes. Before Virtual:

    Class A {public: int a; };

    Class B : public A

    {public: int b; };

    Class C : public A

    {public: int c; };

    Class D : public B, Public C

    {public: int d; };

    After Virtual:Class A {public: int a; };

    Class B : public Virtual A //Virtual Declaration

    {public: int b; };

    Class C : Virtual public A Virtual Keyword can be used in either order

    {public: int c; };

    Class D : public B, Public C

    {public: int d; };

    Program to declare Vir tual Base Classes:

    Class A1 {public: int a1; };

    Class A2 : public Virtual A1 //Virtual Declaration

    {public: int a2; };

    Class A3 : Virtual public A1

    {public: int a3; };

    Class A4 : public A2, Public A3

    {

    public:

    int a4;void get( )

    Ambiguity occurs in accessing the

    base class member variable

  • 8/12/2019 Cs2203 Oops 16marks

    28/46

    28

    {

    couta1>>a2>>a3>>a4;

    }

    void put( )

    {cout

  • 8/12/2019 Cs2203 Oops 16marks

    29/46

    29

    In the above program the class A1 acts as a Abstract Class. Though the classes A2 and

    A3 are also not contributing for the program it can declare as a Virtual so it can act as a virtual

    one. If the keyword isnt present in the declaration then it can also act as an abstract class.

    3.Write short notes on Virtual Function and Pure Virtual Functions?Virtual Function:

    The Virtual keyword prevents the compiler from Early Binding.

    Virtual Function of a base class can be redefined in the derived class. The programmer can use a virtual function in a base class and can use the same

    function name in any derived class even if the number and type of arguments are

    matching.

    The matching function overrides the base class function of same name. It can onlybe a member function.

    Calling of the function without virtual keyword is int b::get(int) If two functions having same name but different arguments then the C++ compiler

    considers them as a different one that is a normal function.

    Syntaxfor declaring a virtual function,

    Pointer variable -> function name;

    Example:

    *point -> get(int);

    Rules for Virtual Functions:

    It shouldnt be static and must be a member of a class. Object pointer can access the virtual function. A virtual function may be declared as

    Friend for another class.

    Constructors cant be declared as a virtual but the destructor can be declared asvirtual.

    Virtual functions may have return values.Program to Use Poin ter for Both Base Class and Derived Class and Cal l the Member

    Function Using Vir tual Keyword:

    Class super

    {

    public:

    virtual void display( )

    {

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    30/46

    30

    virtual void show( )

    {

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    31/46

    31

    The derived class without pure virtual functions is called as Concrete Class.Syntax:

    virtual return-type function-name() = 0

    Example:

    virtual void display( ) = 0;

    The zero is used to instruct the compiler that the function is a pure virtual function and

    it will not have a definition.

    Program for Pure Vir tual F unction in Base Class:

    Class first

    {

    public:int b;

    first( ) { b = 10; }

    virtual void display( ) = 0; // Pure Virtual Function

    };

    Class second : public first

    {

    public:

    int d;

    second( ) { d = 10; }

    void display( )

    {

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    32/46

    32

    Dynamic Casting:

    Its a type of RTTI component but doesnt give what type of object a pointer points tothe user instead it safely converts from a pointer to base type to a pointer to a derived

    type.

    This can be used to convert polymorphic types.Syntax:

    dynamic_cast (object or pointer)

    This converts pointer to the Type*

    Example:

    Class base { };

    Class derived : public base { };int main( )

    {

    base b;

    derived d;

    base *pb=dynamic_cast (&d); (Derived to Base)

    derived *pd=dynamic_cast (&b); (Base to Derived but cant access)

    return 0;

    }

    Down Casting:

    The conversion of pointer or reference to the derived class to pointer or reference tothe base class is UP CASTING.

    Then the reverse is the DOWN CASTING. This can be achieved by explicitly bydynamic casting.

    Example:

    Class base

    {

    virtual void vf( ) { }

    };

    Class derived : public base( ) { };

    int main( )

    {

    base b; derived d;

    derived *pd = dynamic_cast (&b);return 0;

  • 8/12/2019 Cs2203 Oops 16marks

    33/46

    33

    }

    Cross Casting:

    Another dynamic cast feature is Cross Casting.

    Class A { public : virtual ~A( ); };

    Class B { public : virtual ~B( ); };

    Class C : public A, public B { };

    A* ap = new C;

    B* bp = dynamic_cast (ap);

    Classes A & B are completely unrelated. By creating an instance to C it can be safely

    up cast to A*. Then the pointer to A can be (ap) cross casting to pointer B. In this the A

    pointer ap really points at object C. C derives from B.

    UnitV

    1.Explain Streams in C++ in detail.The stream is an intermediator or an interface between I/O devices and the user.

    The standard C++ library contains the I/O stream functions. A library is nothing but aset of .obj files.

    Stream is a flow of data in bytes in sequence. If the data is received from i/p devices in sequence then its called as Source or Input

    Stream.

    If the data is passed to o/p devices in sequence then its called as Destination or OutputStream.

    Input Device

    (Keyboard)

    Output Device

    (Monitor)

    Program

    Extraction from I / P Stream

    Insertion to O / P Stream

    I / P Stream

    O / P Stream

  • 8/12/2019 Cs2203 Oops 16marks

    34/46

    34

    PreDefined Streams:

    Its also called as standard I / O object. These streams are automatically activated when the program execution starts. Some of the predefined streams are cin, cout, clog and cerr. Frequently used unformatted i/p function with cin object

    Cin:standard i/p usually keyboards corresponding to stdin in c.

    Frequently used unformatted i/p function with cout object, Cout:standard o/p usually keyboards corresponding to stdout in c

    Clog:It controls errors message that are passed from buffer to the standard errordevice. A fully buffered version of Cerr.

    Cerr: It controls the unbuffered output data. It catches the error and passes tostandard error device monitor.

    Formatting means representation of data with different settings as per therequirement of the user. The various settings that can be done are number format, fieldwidth etc.

    Cin

    Getline()

    Read ()

    Get ()

    Cout

    Put

    Write

    Flush ()

  • 8/12/2019 Cs2203 Oops 16marks

    35/46

    35

    Unformatted means the data accepted or printed with default settings.Stream Classes:

    C++ streams are based on class and object theory. C++ has number of classes that are used to work with console and file operation. These

    classes are called stream classes.

    In this ios is the base class for istream (i/p) and ostream (o/p) which are in turn baseclasses for iostream (I/O).

    The classes ios can be declared as virtual base class so that, only one copy of itsmembers are inherited by the iostream.

    The class ios has an ability to handle formatted and unformatted data. The istream gives support for both formatted and unformatted data but the ostream can

    handle the formatting data only.

    2.Explain Formatted I / O Operations in detail.C++ provides various formatted console I/O functions for formatting o/p.

    The various types are,

    ios class function and flags, Manipulators, User defined o/p functions

    Ios grants operations common to both i/p and o/p. the formatted o/p functions supported by

    cout object are,

    ios

    streambufistream ostream

    iostream

    ostream_withassigniostream_withassignistream_withassign

    Cout

    Width ()

    Precision ()

    Fill ()

  • 8/12/2019 Cs2203 Oops 16marks

    36/46

    36

    Ios Class Functions:

    Width ()To set the required field width. Output will be displayed in given width. Precision ()To set the number of decimal point for a float value. Fill ()To set a character to fill in the blank space of the field. Setf ()To set various flags for formatting o/p. Unsetf ()To remove flag setting.

    Ios::Width( ):The width () function can be declared in two ways.

    Declaration:

    a) int width();If this function is declared as this it returns to the present width setting.

    b) int width(int);If this function is declared, it sets the width as per the given integer and

    returns the previous width setting. The setting should be reset for each

    I/p or o/p value if width other than the default.

    Program to Set Column Width and Di splay the Character at Specif ied Posit ion :

    void main ( ){

    cout.width (5);

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    37/46

    37

    A B

    Ios::Precision( ):The precision () function can be declared in two ways.

    Declaration:

    a) int precision();

    It returns the current setting of floating point precision.

    b) int precision(int);

    If this function is declared, it sets the floating point precision and returns the

    previous setting.

    Program to Set Precision to two and Display the F loat Number:

    void main ( )

    {

    cout.precision (2);

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    38/46

    38

    / / W E L

    Ios::Setf( ):The set flag setf() function can be declared in two ways.

    Declaration:

    a) long setf(long);

    It sets the flags according to those marked in the given long.

    b) long setf(long sb, long f);

    The bits according to that marked in variable f are removed in the data memberx_flags and then reset to those marked in variable sb.

    Example:

    cout.fill(*);

    cout.setf(ios::left, ios::adjustfield);

    cout.width(5);

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    39/46

    39

    Setfill(char f) Set the fill character to f Fill ( )

    Setiosflags(long l) Set the format flag to l Setf ( )

    Program to display the Formatted Output using Manipul ators:

    #include

    #include

    main ( )

    {

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    40/46

    40

    #include

    #include < iomanip.h>

    ostream & tab (ostream & O)

    {

    O

  • 8/12/2019 Cs2203 Oops 16marks

    41/46

    41

    Details of File Stream Classes:

    CLASSES DESCRIPTION

    Filebuf

    Its purpose is to set the file buffers to read and write. It

    holds constant open prot used in function open ( ) and close

    ( ) as a member.

    FstreambaseServe as a base for fstream, ifstream and ofstream class

    which contains open ( ) and close ( ) function.

    IfstreamProvides i/p operation contains open ( ) with default i/p

    mode. Inherits the function get ( ), read ( ) from istream.

    OfstreamProvides o/p operation contains open ( ) with default i/p

    mode. Inherits the function put ( ), write ( ) from ostream.

    Fstream

    Contains open ( ) with default i/p mode. Inherits all

    function from istream and ostream classes through

    iostream.

    5.Explain ANSI String Objects and Namespaces in detail.ANSI String Object:

    A String is nothing but a sequence of characters. String contains small and capital letters,

    numbers and symbols. It is an array of character type. Each element of string occupies a byte in

    a memory. The last character of string is null ( \0) character.

    String class can be used for the manipulation of the string in C++. String class may

    contain constructors, member functions and operators. By these string class the user can,

    Create String Object Reading and Displaying the String Object Modifying, Adding, Comparing and Accessing the String Object.

    String Constructor:

  • 8/12/2019 Cs2203 Oops 16marks

    42/46

    42

    String ( ) Produces an empty string

    String (const char*text)

    Produces a string object from a null

    ended string

    String (const string&text)Produces a string object from other

    string object

    The declaration and initialization of string object is,

    String text; // Using Constructor without Argument

    String text (C++); // Using Constructor with One Argument

    Text1 = text2; // Assignment of Two Strings

    The Operators used in string manipulators are,

    OPERATOR WORKING

    = Assignment

    + Joining two or more strings

    += Concatenation And Assignment

    ==, !=, =

    Equal To, Not Equal To, Lesser

    Than, Less Than Or Equal,

    Greater Than, Greater Than Or

    Equal

    [ ] Subscript

    > extraction

  • 8/12/2019 Cs2203 Oops 16marks

    43/46

    43

    Program to declare str ing object to perform assignment and concatenation operations:

    #include // String Container

    int main ( ){

    string text;

    string text1 (C++); // Constructor without argument

    string text2 (OOP); // Constructor with argument

    cout

  • 8/12/2019 Cs2203 Oops 16marks

    44/46

    44

    return 0;

    }

    Output:

    s1 = abcAfter Append

    s1 = abchij

    Namespaces:

    C++ allows variables with different scopes such as global, local with different blocks

    and classes. This can be done by using keyword namespace which was introduced by ANSI

    C++. The C++ Standard Library is the best example for namespace. The statement Namespace

    Std tells the compiler that the members of this namespace are to be used in the current

    program.

    Declaration:

    Declaration of namespace is as same as class declaration except that the namespaces are

    not terminated with semicolon.

    Namespace namespace_identifier

    {

    // Definitions of variables, functions and class

    }

    Example:

    Namespace num

    {

    int n;

    void show (int k) {cout

  • 8/12/2019 Cs2203 Oops 16marks

    45/46

    45

    It allows access to only the given elements

    Examples:

    1. Using namespace numN = 10;

    Show (15);

    2. Using namespace :: nM = 20;

    Show (14);

    Nested Namespaces:

    When one namespace is nested in another namespace it is known as nested namespace.

    Example:

    Namespace num

    {

    statement 1;

    Namespace num1

    {

    int k = 0;

    }

    Statement 2;

    }

    The variable k can be accessed as cout

  • 8/12/2019 Cs2203 Oops 16marks

    46/46

    cout