c Program Full

download c Program Full

of 132

Transcript of c Program Full

  • 8/10/2019 c Program Full

    1/132

    Explain the file handling mechanism of c++?Explain the different modes of file handling?

    Give an eg to read and write data to and from a file?

    File. The information / data stored under a specific name on a storage device, is called a file.

    Stream.It refers to a sequence of bytes.Text file.It is a file that stores information in ASCII characters. In text files, each line of text is

    terminated with a special character known as EOL (End of Line) character or delimiter character.

    When this EOL character is read or written, certain internal translations take place.

    Binary file.It is a file that contains information in the same format as it is held in memory. In

    binary files, no delimiters are used for a line and no translations occur here.Classes for file stream operation

    ofstream: Stream class to write on files

    ifstream: Stream class to read from files

    fstream:Stream class to both read and write from/to files.

    Opening a file

    OPENING FILE USING CONSTRUCTOR

    ofstream outFile("sample.txt"); //output only

    ifstream inFile(sample.txt); //input only

    OPENING FILE USING open()

    Stream-object.open(filename, mode)

    ofstream outFile;

    outFile.open("sample.txt");

    ifstream inFile;inFile.open("sample.txt");

    File mode parameter Meaning

    ios::app Append to end of file

    ios::ate go to end of file on opening

    ios::binary file open in binary mode

    ios::in open file for reading only

    ios::out open file for writing only

    ios::nocreate open fails if the file does not exist

    ios::noreplace open fails if the file already exist

  • 8/10/2019 c Program Full

    2/132

    ios::trunc delete the contents of the file if it exist

    All these flags can be combined using the bitwise operator OR (|). For example, if we want to

    open the file example.bin in binary mode to add data we could do it by the following call to

    member function open():

    fstream file;

    file.open ("example.bin", ios::out | ios::app | ios::binary);Closing File

    outFile.close();

    inFile.close();INPUT AND OUTPUT OPERATION

    put() and get() function

    the function put() writes a single character to the associated stream. Similarly, the function get()

    reads a single character form the associated stream.

    example :file.get(ch);

    file.put(ch);

    write() and read() function

    write() and read() functions write and read blocks of binary data.

    example:

    file.read((char *)&obj, sizeof(obj));

    file.write((char *)&obj, sizeof(obj));ERROR HANDLING FUNCTION

    FUNCTION RETURN VALUE AND MEANING

    eof()returns true (non zero) if end of file is encountered whilereading; otherwise return false(zero)

    fail() return true when an input or output operation has failed

    bad()returns true if an invalid operation is attempted or anyunrecoverable error has occurred.

    good() returns true if no error has occurred.

    File Pointers And Their Manipulation

    All i/o streams objects have, at least, one internal stream pointer:

    ifstream, like istream, has a pointer known as the get pointer that points to the element to be read

    in the next input operation.

  • 8/10/2019 c Program Full

    3/132

    ofstream, like ostream, has a pointer known as the put pointer that points to the location where

    the next element has to be written.

    Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived

    from both istream and ostream).

    These internal stream pointers that point to the reading or writing locations within a stream can

    be manipulated using the following member functions:

    seekg() moves get pointer(input) to a specified location

    seekp() moves put pointer (output) to a specified location

    tellg() gives the current position of the get pointer

    tellp() gives the current position of the put pointer

    The other prototype for these functions is:

    seekg(offset, refposition );

    seekp(offset, refposition );

    The parameter offset represents the number of bytes the file pointer is to be moved from the

    location specified by the parameter refposition. The refposition takes one of the following three

    constants defined in the ios class.

    ios::beg start of the file

    ios::cur current position of the pointer

    ios::end end of the file

    example:

    file.seekg(-10, ios::cur);

    Read & Write Example:

    Following is the C++ program which opens a file in reading and writing mode. After writinginformation inputted by the user to a file named afile.dat, the program reads information from the

    file and outputs it onto the screen:#include #include using namespace std;

    int main (){

  • 8/10/2019 c Program Full

    4/132

    char data[100];

    // open a file in write mode.ofstream outfile;outfile.open("afile.dat");

    cout

  • 8/10/2019 c Program Full

    5/132

    Writing to the fileEnter your name: ZaraEnter your age: 9Reading from the fileZara

    How is an Exception Handle in c++? Explain with suitable example?

    An exception is a problem that arises during the execution of a program. A C++ exception is aresponse to an exceptional circumstance that arises while a program is running, such as anattempt to divide by zero.Exceptions provide a way to transfer control from one part of a program to another. C++exception handling is built upon three keywords: try, catch,and throw.

    throw:A program throws an exception when a problem shows up. This is done usinga throwkeyword.

    catch:A program catches an exception with an exception handler at the place in aprogram where you want to handle the problem. The catchkeyword indicates the catching of anexception.

    try:A tryblock identifies a block of code for which particular exceptions will beactivated. It's followed by one or more catch blocks.Assuming a block will raise an exception, a method catches an exception using a combination ofthetryand catchkeywords. A try/catch block is placed around the code that might generate anexception. Code within a try/catch block is referred to as protected code, and the syntax for usingtry/catch looks like the following:

    try{

    // protected code}catch( ExceptionName e1 ){

    // catch block}catch( ExceptionName e2 ){

    // catch block}catch( ExceptionName eN ){

    // catch block}

    You can list down multiple catchstatements to catch different type of exceptions in caseyour tryblock raises more than one exception in different situations.

    Throwing Exceptions:Exceptions can be thrown anywhere within a code block using throwstatements. The operand ofthe throw statements determines a type for the exception and can be any expression and the typeof the result of the expression determines the type of exception thrown.

    Following is an example of throwing an exception when dividing by zero condition occurs:

  • 8/10/2019 c Program Full

    6/132

    double division(int a, int b){

    if( b == 0 ){

    throw "Division by zero condition!";

    }return (a/b);

    }

    Catching Exceptions:The catchblock following the try block catches any exception. You can specify what type ofexception you want to catch and this is determined by the exception declaration that appears inparentheses following the keyword catch.

    try{

    // protected code

    }catch( ExceptionName e ){

    // code to handle ExceptionName exception}

    Above code will catch an exception of ExceptionNametype. If you want to specify that a catchblock should handle any type of exception that is thrown in a try block, you must put an ellipsis,..., between the parentheses enclosing the exception declaration as follows:

    try{

    // protected code

    }catch(...){// code to handle any exception

    }

    The following is an example, which throws a division by zero exception and we catch it in catchblock.

    #include using namespace std;

    double division(int a, int b)

    {if( b == 0 ){

    throw "Division by zero condition!";}return (a/b);

    }

  • 8/10/2019 c Program Full

    7/132

    int main (){

    int x = 50;int y = 0;double z = 0;

    try {z = division(x, y);cout

  • 8/10/2019 c Program Full

    8/132

    std::out_of_rangeThis can be thrown by the at method from for example astd::vector and std::bitset::operator[]().

    std::runtime_errorAn exception that theoretically can not be detected by readingthe code.

    std::overflow_error This is thrown if a mathematical overflow occurs.

    std::range_errorThis is occured when you try to store a value which is out ofrange.

    std::underflow_error This is thrown if a mathematical underflow occurs.

    Define New Exceptions:You can define your own exceptions by inheriting and overriding exceptionclass functionality.Following is the example, which shows how you can use std::exception class to implement yourown exception in standard way:

    #include #include using namespace std;

    struct MyException : public exception{

    const char * what () const throw (){return "C++ Exception";

    }};

    int main(){try{throw MyException();

    }catch(MyException& e){std::cout

  • 8/10/2019 c Program Full

    9/132

    MyException caughtC++ Exception

    Here, what()is a public method provided by exception class and it has been overridden by all thechild exception classes. This returns the cause of an exception.

    Wap to demonstrate overloading of operator + to add 2 complex number using friend

    function?

    Some of the most commonly used operators in C++ are the arithmetic operators that is, the

    plus operator (+), minus operator (-), multiplication operator (*), and division operator (/). Note

    that all of the arithmetic operators are binary operators meaning they take two operands

    one on each side of the operator. All four of these operators are overloaded in the exact same

    way.

    Overloading operators using friend functions

    When the operator does not modify its operands, the best way to overload the operator is via

    friend function. None of the arithmetic operators modify their operands (they just produce and

    return a result), so we will utilize the friend function overloaded operator method here.

    The following example shows how to overload operator plus (+) in order to add two Cents

    objects together:

    Operators can be overloaded in c++ with friend functions also. The procedure is same as wediscussed earlier. Here I will demonstrate operator overloading with "+" operator which is abinary operator. I will be using a complex number class (called complex). The class will have 2data types, real and imaginary.Operator overloading will not be a part of class complex, but we will declare that this function isa friend of class complex.

    Note that since overloaded function is not part of class , so will require 2 args (overloading withmember function require 1 arg for binary operator, as the first arg is the object itself.)Use:Most student wonder why we need to use operator overloading in such manner? The answer issimple, this will allow you to manipulate operator for predefined objects that you mat not haveaccess. (Like cout or cin)

    Code:#includeusingnamespacestd;// complex class with real and imaginary partclasscomplex{

    public:intreal;intimg;//default constructor

  • 8/10/2019 c Program Full

    10/132

    complex(){

    real=img=0;}//overloaded constructor with 2 args

    complex(intx,inty){real=x;img=y;

    }//show function to display complex numbervoidshow(){

    cout

  • 8/10/2019 c Program Full

    11/132

    Methods name and signatures must be same. Having same method name with different

    Signatures.

    Overriding is the concept of runtime

    polymorphism

    Overloading is the concept of compile time

    polymorphism

    When a function of base class is re-defined inthe derived class called as Overriding

    Two functions having same name and returntype, but with different type and/or number of

    arguments is called as Overloading

    It needs inheritance. It doesn't need inheritance.

    Method should have same data type. Method can have different data types

    Method should be public. Method can be different access specifies

    Example

    Overriding

    public class MyBaseClass

    {

    public virtual void MyMethod()

    {

    Console.Write("My BaseClass Method");

    }

    }

    public class MyDerivedClass : MyBaseClass{

    public override void MyMethod()

    {

    Console.Write("My DerivedClass Method");

    }

    }

    Overloading

    int add(int a, int b)

    int add(float a , float b)

    Explain the concepts of oops supported by example?

  • 8/10/2019 c Program Full

    12/132

    In this tutorial you will learn about Objects, Classes, Inheritance, Data Abstraction, Data

    Encapsulation, Polymorphism, Overloading, and Reusability.

    Before starting to learn C++ it is essential to have a basic knowledge of the concepts of Object

    oriented programming. Some of the important object oriented features are namely:

    Objects

    Classes

    Inheritance

    Data Abstraction

    Data Encapsulation

    Polymorphism

    Overloading

    Reusability

    In order to understand the basic concepts in C++, a programmer must have a good knowledge ofthe basic terminology in object-oriented programming. Below is a brief outline of the concepts of

    object-oriented programming languages :

    Objects:

    Object is the basic unit of object-oriented programming. Objects are identified by its unique

    name. An object represents a particular instance of a class. There can be more than one instance

    of a class. Each instance of a class can hold its own relevant data.

    An Object is a collection of data members and associated member functions also known asmethods.

    Classes:

    Classes are data types based on which objects are created. Objects with similar properties and

    methods are grouped together to form a Class. Thus a Class represents a set of individual objects.

  • 8/10/2019 c Program Full

    13/132

    Characteristics of an object are represented in a class as Properties. The actions that can be

    performed by objects become functions of the class and are referred to as Methods.

    For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR

    represents individual Objects. In this context each Car Object will have its own, Model, Year of

    Manufacture, Color, Top Speed, Engine Power etc., which form Properties of the Car class and

    the associated actions i.e., object functions like Start, Move, and Stop form the Methods of Car

    Class.

    No memory is allocated when a class is created. Memory is allocated only when an object is

    created, i.e., when an instance of a class is created.

    Inheritance:

    Inheritance is the process of forming a new class from an existing class or base class. The base

    class is also known as parent class or super class. The new class that is formed is called derived

    class. Derived class is also known as a child class or sub class. Inheritance helps in reducing the

    overall code size of the program, which is an important concept in object-oriented programming.

    Data Abstraction:

    Data Abstraction increases the power of programming language by creating user defined data

    types. Data Abstraction also represents the needed information in the program without presenting

    the details.

    Data Encapsulation:

    Data Encapsulation combines data and functions into a single unit called Class. When using Data

    Encapsulation, data is not accessed directly; it is only accessible through the functions present

    inside the class. Data Encapsulation enables the important concept of data hiding possible.

    Polymorphism:

    Polymorphism allows routines to use variables of different types at different times. An operator

    or function can be given different meanings or functions. Polymorphism refers to a single

    function or multi-functioning operator performing in different ways.

    Overloading:

    Overloading is one type of Polymorphism. It allows an object to have different meanings,

    depending on its context. When an existing operator or function begins to operate on new data

    type, or class, it is understood to be overloaded.

  • 8/10/2019 c Program Full

    14/132

    Reusability:

    This term refers to the ability for multiple programmers to use the same written and debugged

    existing class of data. This is a time saving device and adds code efficiency to the language.

    Additionally, the programmer can incorporate new features to the existing class, further

    developing the application and allowing users to achieve increased performance. This timesaving feature optimizes code, helps in gaining secured applications and facilitates easier

    maintenance on the application.

    The implementation of each of the above object-oriented programming features for C++ will be

    highlighted in later sections.

    A sample program to understand the basic structure of C++

    1. //program to read employee details and to output the data

    2.3. ////////// code begins here /////////////////////////////

    4. #include< iostream > // Preprocessor directive

    5. using namespace std;

    6. class employee // Class Declaration

    7. {

    8. private:

    9. char empname[50];

    10. int empno;

    11.

    12. public:

    13. void getvalue()

    14. {

    15. coutempname; //

    waiting input from the Keyboard for the name

    17. coutempno; // waiting

    input from the Keyboard for the number

    19. }

    20. void displayvalue(){

    21. cout

  • 8/10/2019 c Program Full

    15/132

    23.

    24. }

    25. };

    26. void main()

    27. {28. employee e1; // Creation of Object

    29. e1.getvalue(); // the getvalue method is

    being called

    30. e1.displayvalue(); // the displayvalue method is being called

    31. }

    32.

    33. ///// code ends here //////////////

    Output:

    Data Encapsulation

    All C++ programs are composed of the following two fundamental elements:

    Program statements (code):This is the part of a program that performs actions and theyare called functions.

    Program data:The data is the information of the program which affected by theprogram functions.Encapsulation is an Object Oriented Programming concept that binds together the data andfunctions that manipulate the data, and that keeps both safe from outside interference and misuse.

    Data encapsulation led to the important OOP concept of data hiding.Data encapsulationis a mechanism of bundling the data, and the functions that use themand data abstractionis a mechanism of exposing only the interfaces and hiding theimplementation details from the user.C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied that a class can contain private,protected and publicmembers. By default, all items defined in a class are private. For example:

    class Box

  • 8/10/2019 c Program Full

    16/132

    {public:

    double getVolume(void){

    return length * breadth * height;

    }private:

    double length; // Length of a boxdouble breadth; // Breadth of a boxdouble height; // Height of a box

    };

    The variables length, breadth, and height are private. This means that they can be accessed onlyby other members of the Box class, and not by any other part of your program. This is one wayencapsulation is achieved.To make parts of a class public(i.e., accessible to other parts of your program), you must declarethem after the publickeyword. All variables or functions defined after the public specifier are

    accessible by all other functions in your program.

    Making one class a friend of another exposes the implementation details and reducesencapsulation. The ideal is to keep as many of the details of each class hidden from all otherclasses as possible.

    Data Encapsulation Example:

    Any C++ program where you implement a class with public and private members is an exampleof data encapsulation and data abstraction. Consider the following example:

    #include using namespace std;

    class Adder{public:

    // constructorAdder(int i = 0){total = i;

    }// interface to outside world

    void addNum(int number){

    total += number;}// interface to outside worldint getTotal(){

    return total;

  • 8/10/2019 c Program Full

    17/132

    };private:

    // hidden data from outside worldint total;

    };

    int main( ){

    Adder a;

    a.addNum(10);a.addNum(20);a.addNum(30);

    cout

  • 8/10/2019 c Program Full

    18/132

    When you define a class, you define a blueprint for a data type. This doesn't actually define anydata, but it does define what the class name means, that is, what an object of the class will consistof and what operations can be performed on such an object.

    A class definition starts with the keyword classfollowed by the class name; and the class body,

    enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or alist of declarations. For example, we defined the Box data type using the keyword classasfollows:

    class Box{

    public:double length; // Length of a boxdouble breadth; // Breadth of a boxdouble height; // Height of a box

    };

    The keyword publicdetermines the access attributes of the members of the class that follow it. A

    public member can be accessed from outside the class anywhere within the scope of the classobject. You can also specify the members of a class as privateor protected which we willdiscuss in a sub-section.

    Define C++ Objects:

    A class provides the blueprints for objects, so basically an object is created from a class. Wedeclare objects of a class with exactly the same sort of declaration that we declare variables ofbasic types. Following statements declare two objects of class Box:

    Box Box1; // Declare Box1 of type BoxBox Box2; // Declare Box2 of type Box

    Both of the objects Box1 and Box2 will have their own copy of data members.

    Accessing the Data Members:

    The public data members of objects of a class can be accessed using the direct member accessoperator (.). Let us try the following example to make the things clear:

    #include

    using namespace std;

    class Box{

    public:double length; // Length of a boxdouble breadth; // Breadth of a boxdouble height; // Height of a box

  • 8/10/2019 c Program Full

    19/132

    };

    int main( ){

    Box Box1; // Declare Box1 of type Box

    Box Box2; // Declare Box2 of type Boxdouble volume = 0.0; // Store the volume of a box here

    // box 1 specificationBox1.height = 5.0;Box1.length = 6.0;Box1.breadth = 7.0;

    // box 2 specificationBox2.height = 10.0;Box2.length = 12.0;

    Box2.breadth = 13.0;// volume of box 1volume = Box1.height * Box1.length * Box1.breadth;cout

  • 8/10/2019 c Program Full

    20/132

    Class member functions

    A member function of a class is a function that has

    its definition or its prototype within the class

    definition like any other variable.

    Class access modifiers A class member can be defined as public, privateor protected. By default members would be

    assumed as private.

    Constructor & destructor

    A class constructor is a special function in a class

    that is called when a new object of the class is

    created. A destructor is also a special function

    which is called when created object is deleted.

    C++ copy constructor

    The copy constructor is a constructor which

    creates an object by initializing it with an object of

    the same class, which has been created previously.

    C++ friend functions A friendfunction is permitted full access to

    private and protected members of a class.

    C++ inline functions

    With an inline function, the compiler tries to

    expand the code in the body of the function in

    place of a call to the function.

    The this pointer in C++ Every object has a special pointer thiswhich

    points to the object itself.

    Pointer to C++ classes

    A pointer to a class is done exactly the same way a

    pointer to a structure is. In fact a class is really just

    a structure with functions in it.

    Static members of a class Both data members and function members of a

    class can be declared as static.

    Inheritance

    One of the most important concepts in object-oriented programming is that of inheritance.Inheritance allows us to define a class in terms of another class, which makes it easier to create

  • 8/10/2019 c Program Full

    21/132

    and maintain an application. This also provides an opportunity to reuse the code functionalityand fast implementation time.

    When creating a class, instead of writing completely new data members and member functions,the programmer can designate that the new class should inherit the members of an existing class.

    This existing class is called thebase

    class, and the new class is referred to as thederived

    class.The idea of inheritance implements the is arelationship. For example, mammal IS-A animal, dogIS-A mammal hence dog IS-A animal as well and so on.

    Base & Derived Classes:

    A class can be derived from more than one classes, which means it can inherit data and functionsfrom multiple base classes. To define a derived class, we use a class derivation list to specify thebase class(es). A class derivation list names one or more base classes and has the form:

    class derived-class: access-specifier base-class

    Where access-specifier is one of public, protected,or private, and base-class is the name of a

    previously defined class. If the access-specifier is not used, then it is private by default.Consider a base class Shapeand its derived class Rectangleas follows:

    #include

    using namespace std;

    // Base classclass Shape{

    public:void setWidth(int w){

    width = w;}void setHeight(int h){

    height = h;}

    protected:int width;int height;

    };

    // Derived classclass Rectangle: public Shape{

    public:int getArea(){

    return (width * height);

  • 8/10/2019 c Program Full

    22/132

    }};

    int main(void){

    Rectangle Rect;

    Rect.setWidth(5);Rect.setHeight(7);

    // Print the area of the object.cout

  • 8/10/2019 c Program Full

    23/132

    When deriving a class from a base class, the base class may be inherited through public,protectedorprivate inheritance. The type of inheritance is specified by the access-specifier asexplained above.We hardly use protectedor privateinheritance, but publicinheritance is commonly used.While using different type of inheritance, following rules are applied:

    Public Inheritance:When deriving a class from a publicbase class, publicmembers ofthe base class become publicmembers of the derived class and protectedmembers of the baseclass become protectedmembers of the derived class. A base class's privatemembers are neveraccessible directly from a derived class, but can be accessed through calls tothe publicand protectedmembers of the base class.

    Protected Inheritance:When deriving from a protectedbaseclass, publicand protectedmembers of the base class become protectedmembers of the derivedclass.

    Private Inheritance:When deriving from a privatebaseclass, publicand protectedmembers of the base class become privatemembers of the derivedclass.

    Multiple Inheritances:

    A C++ class can inherit members from more than one class and here is the extended syntax:

    class derived-class: access baseA, access baseB....

    Where access is one of public, protected,or privateand would be given for every base classand they will be separated by comma as shown above. Let us try the following example:

    #include

    using namespace std;

    // Base class Shapeclass Shape{

    public:void setWidth(int w){

    width = w;}void setHeight(int h){

    height = h;}

    protected:int width;int height;

    };

    // Base class PaintCost

  • 8/10/2019 c Program Full

    24/132

    class PaintCost{

    public:int getCost(int area){

    return area * 70;}

    };

    // Derived classclass Rectangle: public Shape, public PaintCost{

    public:int getArea(){

    return (width * height);

    }};

    int main(void){

    Rectangle Rect;int area;

    Rect.setWidth(5);Rect.setHeight(7);

    area = Rect.getArea();

    // Print the area of the object.cout

  • 8/10/2019 c Program Full

    25/132

    Oveloading Operator & Function

    C++ allows you to specify more than one definition for a functionname or an operatorin thesame scope, which is called function overloadingand operator overloadingrespectively.

    An overloaded declaration is a declaration that had been declared with the same name as apreviously declared declaration in the same scope, except that both declarations have differentarguments and obviously different definition (implementation).

    When you call an overloaded functionor operator, the compiler determines the mostappropriate definition to use by comparing the argument types you used to call the function oroperator with the parameter types specified in the definitions. The process of selecting the mostappropriate overloaded function or operator is called overload resolution.

    Function overloading in C++:

    You can have multiple definitions for the same function name in the same scope. The definitionof the function must differ from each other by the types and/or the number of arguments in theargument list. You can not overload function declarations that differ only by return type.

    Following is the example where same function print()is being used to print different data types:

    #include using namespace std;

    class printData{

    public:void print(int i) {cout

  • 8/10/2019 c Program Full

    26/132

    // Call print to print characterpd.print("Hello C++");

    return 0;}

    When the above code is compiled and executed, it produces the following result:

    Printing int: 5Printing float: 500.263Printing character: Hello C++

    Operators overloading in C++:

    You can redefine or overload most of the built-in operators available in C++. Thus a programmercan use operators with user-defined types as well.

    Overloaded operators are functions with special names the keyword operator followed by thesymbol for the operator being defined. Like any other function, an overloaded operator has areturn type and a parameter list.

    Box operator+(const Box&);

    declares the addition operator that can be used to add two Box objects and returns final Boxobject. Most overloaded operators may be defined as ordinary non-member functions or as classmember functions. In case we define above function as non-member function of a class then wewould have to pass two arguments for each operand as follows:

    Box operator+(const Box&, const Box&);

    Following is the example to show the concept of operator over loading using a member function.Here an object is passed as an argument whose properties will be accessed using this object, theobject which will call this operator can be accessed using thisoperator as explained below:

    #include using namespace std;

    class Box{

    public:

    double getVolume(void){

    return length * breadth * height;}void setLength( double len ){

    length = len;}

  • 8/10/2019 c Program Full

    27/132

    void setBreadth( double bre ){

    breadth = bre;}

    void setHeight( double hei ){

    height = hei;}// Overload + operator to add two Box objects.Box operator+(const Box& b){

    Box box;box.length = this->length + b.length;box.breadth = this->breadth + b.breadth;

    box.height = this->height + b.height;return box;

    }private:

    double length; // Length of a boxdouble breadth; // Breadth of a boxdouble height; // Height of a box

    };// Main function for the programint main( ){

    Box Box1; // Declare Box1 of type BoxBox Box2; // Declare Box2 of type BoxBox Box3; // Declare Box3 of type Boxdouble volume = 0.0; // Store the volume of a box here

    // box 1 specificationBox1.setLength(6.0);Box1.setBreadth(7.0);Box1.setHeight(5.0);

    // box 2 specification

    Box2.setLength(12.0);Box2.setBreadth(13.0);Box2.setHeight(10.0);

    // volume of box 1volume = Box1.getVolume();cout

  • 8/10/2019 c Program Full

    28/132

    // volume of box 2volume = Box2.getVolume();cout

  • 8/10/2019 c Program Full

    29/132

    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.

    Consider the following example where a base class has been derived by other two classes:

    #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

  • 8/10/2019 c Program Full

    30/132

    Triangle tri(10,5);

    // store the address of Rectangleshape = &rec;// call rectangle area.

    shape->area();

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

    return 0;}

    When the above code is compiled and executed, it produces the following result:

    Parent class areaParent class area

    The reason for the incorrect output is that the call of the function area() is being set once by thecompiler as the version defined in the base class. This is called static resolutionof the functioncall, orstatic linkage - the function call is fixed before the program is executed. This is alsosometimes calledearly bindingbecause the area() function is set during the compilation of theprogram.But now, let's make a slight modification in our program and precede the declaration of area() inthe Shape class with the keyword virtualso that it looks like this:

    class Shape {protected:int width, height;

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

    width = a;height = b;

    }virtual int area(){

    cout

  • 8/10/2019 c Program Full

    31/132

    Rectangle class areaTriangle class area

    This time, the compiler looks at the contents of the pointer instead of it's type. Hence, sinceaddresses of objects of tri and rec classes are stored in *shape the respective area() function is

    called.

    As you can see, each of the child classes has a separate implementation for the function area().This is how polymorphismis generally used. You have different classes with a function of thesame name, and even the same parameters, but with different implementations.

    Virtual Function:

    A virtual function is a function in a base class that is declared using the keyword virtual.Defining in a base class a virtual function, with another version in a derived class, signals to thecompiler that we don't want static linkage for this function.What we do want is the selection of the function to be called at any given point in the program tobe based on the kind of object for which it is called. This sort of operation is referred toas dynamic linkage, or late binding.

    Pure Virtual Functions:

    It's possible that you'd want to include a virtual function in a base class so that it may beredefined in a derived class to suit the objects of that class, but that there is no meaningfuldefinition you could give for the function in the base class.

    We can change the virtual function area() in the base class to the following:

    class Shape {

    protected:int width, height;public:

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

    width = a;height = b;

    }// pure virtual functionvirtual int area() = 0;

    };

    The = 0 tells the compiler that the function has no body and above virtual function will becalled pure virtual function.

    Data Abstraction

  • 8/10/2019 c Program Full

    32/132

    Data abstraction refers to, providing only essential information to the outside world and hidingtheir background details, i.e., to represent the needed information in program without presentingthe details.

    Data abstraction is a programming (and design) technique that relies on the separation of

    interface and implementation.Let's take one real life example of a TV, which you can turn on and off, change the channel,adjust the volume, and add external components such as speakers, VCRs, and DVD players,BUT you do not know its internal details, that is, you do not know how it receives signals overthe air or through a cable, how it translates them, and finally displays them on the screen.

    Thus, we can say a television clearly separates its internal implementation from its externalinterface and you can play with its interfaces like the power button, channel changer, and volumecontrol without having zero knowledge of its internals.

    Now, if we talk in terms of C++ Programming, C++ classes provides great level of data

    abstraction. They provide sufficient public methods to the outside world to play with thefunctionality of the object and to manipulate object data, i.e., state without actually knowing howclass has been implemented internally.For example, your program can make a call to the sort()function without knowing whatalgorithm the function actually uses to sort the given values. In fact, the underlyingimplementation of the sorting functionality could change between releases of the library, and aslong as the interface stays the same, your function call will still work.In C++, we use classesto define our own abstract data types (ADT). You can use the coutobjectof class ostreamto stream data to standard output like this:

    #include using namespace std;

    int main( ){

    cout

  • 8/10/2019 c Program Full

    33/132

    There are no restrictions on how often an access label may appear. Each access label specifiesthe access level of the succeeding member definitions. The specified access level remains ineffect until the next access label is encountered or the closing right brace of the class body isseen.

    Benefits of Data Abstraction:

    Data abstraction provides two important advantages:

    Class internals are protected from inadvertent user-level errors, which might corrupt thestate of the object.

    The class implementation may evolve over time in response to changing requirements orbug reports without requiring change in user-level code.

    By defining data members only in the private section of the class, the class author is free to makechanges in the data. If the implementation changes, only the class code needs to be examined to

    see what affect the change may have. If data are public, then any function that directly accessesthe data members of the old representation might be broken.

    Data Abstraction Example:

    Any C++ program where you implement a class with public and private members is an exampleof data abstraction. Consider the following example:

    #include using namespace std;

    class Adder{public:

    // constructorAdder(int i = 0){total = i;

    }// interface to outside worldvoid addNum(int number){

    total += number;

    }// interface to outside worldint getTotal(){

    return total;};

    private:// hidden data from outside world

  • 8/10/2019 c Program Full

    34/132

    int total;};int main( ){

    Adder a;

    a.addNum(10);a.addNum(20);a.addNum(30);

    cout

  • 8/10/2019 c Program Full

    35/132

    public:// pure virtual functionvirtual double getVolume() = 0;

    private:double length; // Length of a box

    double breadth; // Breadth of a boxdouble height; // Height of a box

    };

    The purpose of an abstract class(often referred to as an ABC) is to provide an appropriate baseclass from which other classes can inherit. Abstract classes cannot be used to instantiate objectsand serves only as an interface. Attempting to instantiate an object of an abstract class causes acompilation error.

    Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtualfunctions, which means that it supports the interface declared by the ABC. Failure to override apure virtual function in a derived class, then attempting to instantiate objects of that class, is a

    compilation error.

    Classes that can be used to instantiate objects are called concrete classes.

    Abstract Class Example:

    Consider the following example where parent class provides an interface to the base class toimplement a function called getArea():

    #include

    using namespace std;

    // Base classclass Shape{public:

    // pure virtual function providing interface framework.virtual int getArea() = 0;void setWidth(int w){

    width = w;}void setHeight(int h)

    { height = h;}

    protected:int width;int height;

    };

  • 8/10/2019 c Program Full

    36/132

    // Derived classesclass Rectangle: public Shape{public:

    int getArea()

    {return (width * height);

    }};class Triangle: public Shape{public:

    int getArea(){

    return (width * height)/2;}

    };

    int main(void){

    Rectangle Rect;Triangle Tri;

    Rect.setWidth(5);Rect.setHeight(7);// Print the area of the object.cout

  • 8/10/2019 c Program Full

    37/132

    An object-oriented system might use an abstract base class to provide a common andstandardized interface appropriate for all the external applications. Then, through inheritancefrom that abstract base class, derived classes are formed that all operate similarly.

    The capabilities (i.e., the public functions) offered by the external applications are provided as

    pure virtual functions in the abstract base class. The implementations of these pure virtualfunctions are provided in the derived classes that correspond to the specific types of theapplication.

    This architecture also allows new applications to be added to a system easily, even after thesystem has been defined.

    Explain the new and delete operator in dynamic memory allocation?

    A good understanding of how dynamic memory really works in C++ is essential to becoming agood C++ programmer. Memory in your C++ program is divided into two parts:

    The stack:All variables declared inside the function will take up memory from the stack. The heap:This is unused memory of the program and can be used to allocate the

    memory dynamically when program runs.

    Many times, you are not aware in advance how much memory you will need to store particularinformation in a defined variable and the size of required memory can be determined at run time.

    You can allocate memory at run time within the heap for the variable of a given type using aspecial operator in C++ which returns the address of the space allocated. This operator is

    called newoperator.If you are not in need of dynamically allocated memory anymore, you can use deleteoperator,which de-allocates memory previously allocated by new operator.

    The new and delete operators:

    There is following generic syntax to use newoperator to allocate memory dynamically for anydata-type.

    new data-type;

    Here, data-typecould be any built-in data type including an array or any user defined data typesinclude class or structure. Let us start with built-in data types. For example we can define apointer to type double and then request that the memory be allocated at execution time. We can

    do this using the newoperator with the following statements:double* pvalue = NULL; // Pointer initialized with nullpvalue = new double; // Request memory for the variable

    The memory may not have been allocated successfully, if the free store had been used up. So it isgood practice to check if new operator is returning NULL pointer and take appropriate action asbelow:

  • 8/10/2019 c Program Full

    38/132

    double* pvalue = NULL;if( !(pvalue = new double )){

    cout

  • 8/10/2019 c Program Full

    39/132

    pvalue = new char[20]; // Request memory for the variable

    To remove the array that we have just created the statement would look like this:

    delete [] pvalue; // Delete array pointed to by pvalue

    Following the similar generic syntax of new operator, you can allocat for a multi-dimensionalarray as follows:

    double** pvalue = NULL; // Pointer initialized with nullpvalue = new double [3][4]; // Allocate memory for a 3x4 array

    However, the syntax to release the memory for multi-dimensional array will still remain same asabove:

    delete [] pvalue; // Delete array pointed to by pvalue

    Dynamic Memory Allocation for Objects:

    Objects are no different from simple data types. For example, consider the following code wherewe are going to use an array of objects to clarify the concept:

    #include using namespace std;

    class Box{

    public:Box() {

    cout

  • 8/10/2019 c Program Full

    40/132

    If you were to allocate an array of four Box objects, the Simple constructor would be called fourtimes and similarly while deleting these objects, destructor will also be called same number oftimes.

    If we compile and run above code, this would produce the following result:

    Constructor called!Constructor called!Constructor called!Constructor called!Destructor called!Destructor called!Destructor called!Destructor called!

    Wap to read 2 integer from keyboard and to perform simple airthematic operation using

    the pointer technique?The memory space for the operator is allocated by the new

    operator?

    Wap a program to define a class vector that operates on vector. write the member function

    to compute the vector product, scalar product ,sum of the element of the vector, average of

    elements, and sum of the square of elements?

    What is containership? How does it differ from inheritance?

    Inheritance vs Containership

    Inheritance and Containership are two important concepts found in OOP (Object Oriented

    Programming Example: C++). In simple terms, both Containership and Inheritance deal with

    providing additional properties or behavior to a class. Inheritance is the ability for a class to

    inherit properties and behavior from a parent class by extending it. On the other hand,

    Containership is the ability of a class to contain objects of different classes as member data.

    What is Inheritance?

    As mentioned above, Inheritance is the ability for a class to inherit properties and behavior from

    a parent class by extending it. Inheritance essentially provides code reuse by allowing extending

    properties and behavior of an existing class by a newly defined class. If class A extends B, then

    class B is called the parent class (or super class) and class A is called the child class (or derived

  • 8/10/2019 c Program Full

    41/132

    class/sub class). In this example scenario, class A will inherit all public and protected attributes

    and methods of the super class (B). The subclass can optionally override (provide new or

    extended functionality to methods) the behavior inherited from the parent class. Inheritance

    represents an is-a relationship in OOP. This essentially means that A is also a B. In other

    words, B can be the class with a general description of a certain real world entity but A specifies

    a certain specialization. In a real world programming problem, the Person class could be

    extended to create the Employee class. This is called specialization. But you could also first

    create the Employee class and then generalize it to a Person class as well (i.e. generalization). In

    this example, the Employee will have all the properties and behavior of the Person (i.e.

    Employee is also a Person) and may contain some additional functionality (so, Person is not an

    Employee) as well.

    What is Containership?

    Containership is the ability of a class to contain objects of different classes as member data. Forexample, class A could contain an object of class B as a member. Here, all the public methods

    (or functions) defined in B can be executed within the class A. Class A becomes the container,

    while class B becomes the contained class. Containership is also referred to as Composition. In

    this example, it can be said that class A is composed of class B. In OOP, Containership

    represents a has-a relationship. It is important to note that, even though the container has

    access to execute all the public methods of the contained class, it is not able to alter or provide

    additional functionality. When it comes to a real world programming problem, an object of class

    TextBox may be contained in the class Form, and thus can be said that a Form contains a

    TextBox (or alternatively, a Form is composed of a TextBox).

    Difference between Inheritance and Containership

    Although Inheritance and Containership are two OOP concepts, they are quite different in what

    they allow the programmer to achieve. Inheritance is the ability for a class to inherit properties

    and behavior from a parent class by extending it, while Containership is the ability of a class to

    contain objects of different classes as member data. If a class is extended, it inherits all the public

    and protected properties/behavior and those behaviors may be overridden by the subclass. But if

    a class is contained in another, the container does not get the ability to change or add behavior to

    the contained. Inheritance represents an is-a relationship in OOP, while Containership

    represents a has-a relationship.

    Differentiate between class and Objects?

    Objects vs Classes

  • 8/10/2019 c Program Full

    42/132

    Objects and classes are used in object oriented programming languages. All object oriented

    programming languages such as C++, Java, .NET and others, employs objects and classes.

    Objects

    An object is defined as any entity that can be utilized by using commands in a programming

    language. Object can be a variable, value, data structure or a function. In object oriented

    environment, object is referred to as instance of a class. Objects and classes are closely related to

    each other. In real world, the objects are your TV, bicycle, desk and other entities. Methods are

    used to access the objects of a class. All the interaction is done through the objects methods.

    This is known as data encapsulation. The objects are also used for data or code hiding.

    A number of benefitsareprovided by the objects when they are used in the code:

    Ease of debugging The object can be easily removed from the code if there is some problem

    due to it. A different object can be plugged in as a replacement of the former one. Information hiding The code or internal implementation is hidden from the users when

    interaction is done through objects methods.

    Reuse of code if an object or code is written by some other programmer then you can also use

    that object in your program. In this way, objects are highly reusable. This allows experts to

    debug, implement task specific and complex objects that can be used in your own code.

    Modularity You can write as well as maintain the source codes of objects in an independent

    manner. This provides modular approach to programming.

    Classes

    A class is a concept used in object oriented programming languages such as C++, PHP, andJAVA etc. Apart from holding data, a class is also used to hold functions. An object is an instant

    of a class. In case of variables, the type is the class whereas the variable is the object. The

    keyword class is used to declare a class and it has the following format:

    class CLASS_NAME

    {

    AccessSpecifier1:

    Member-1;

    AccessSpecifier2:

    Member-2;

    } OBJECT_NAMES;

    Here, the valid identifier is CLASS_NAME and the names for objects are represented by

    OBJECT_NAMES. The benefit of objects include information hiding, modularity, ease in

    debugging and reuse of the code. The body contains the members that can be functions or data

    declarations. The keywords for access specifiers are public, protected or private.

  • 8/10/2019 c Program Full

    43/132

    The public members can be accessed anywhere.

    The protected members can be accessed within same classes or from friend classes.

    The private members can be accessed only within the same class.

    By default, the access is private when the class keyword is used. A class can hold both data and

    functions.

    Objects vs. Classes

    An object is an instant of a class. A class is used to hold data and functions.

    When a class is declared, no memory is allocated but when the object of the class is

    declared, memory is allocated. So, class is just a template.

    An object can only be created if the class is already declared otherwise it is not possible

    Difference between containership and inheritance or derived class in C++

    Containership: Containership is the phenomenon of using one or more classes within the

    definition of other class. When a class contains the definition of some other classes, it is referred

    to as composition, containment or aggregation. The data member of a new class is an object of

    some other class. Thus the other class is said to be composed of other classes and hence referred

    to as containership. Composition is often referred to as a has-a relationship because the

    objects of the composite class have objects of the composed class as members.

    What is a container class? What are the types of container classes?

    A container class is a class that is used to hold objects in memory or external storage. A

    container class acts as a generic holder. A container class has a predefined behavior and a well-

    known interface. A container class is a supporting class whose purpose is to hide the topology

    used for maintaining the list of objects in memory. When a container class contains a group of

    mixed objects, the container is called a heterogeneous container; when the container is holding a

    group of objects that are all the same, the container is called a homogeneous container.

    Inheritance: Inheritance is the phenomenon of deriving a new class from an old one.

    Inheritance supports code reusability. Additional features can be added to a class by deriving aclass from it and then by adding new features to it. Class once written or tested need not be

    rewritten or redefined. Inheritance is also referred to as specialization or derivation, as one class

    is inherited or derived from the other. It is also termed as is-a relationship because every

    object of the class being defined is also an object of the inherited class.

  • 8/10/2019 c Program Full

    44/132

    How is polymorphism achieved in compile time and runtime?

    Compile time Polymorphism:

    C++ support polymorphism. One function multiple purpose, or in short many functions havingsame name but with different function body.For every function call compiler binds the call to one function definition at compile time. This

    decision of binding among several functions is taken by considering formal arguments of thefunction, their data type and their sequence.

    Example of compile time polymorphism:

    Example 1: example of compile time polymorphism; static time binding

    void f(int i){cout

  • 8/10/2019 c Program Full

    45/132

    class Derv: public Base{public:

    void display(int j){ cout

  • 8/10/2019 c Program Full

    46/132

    an integer expression. The switch selection structure is a multiple selection structure, it selectsthe action to perform from many different action states.

    C++ provides three types of repetition structures also called looping structures or loops,namely while, do/while, and for. A repetition structure allows the programmer to specify that a

    program should repeat an action while some condition remains true.posted by Carlos @ 1:30 PM

    If Selection StructurePrograms use selection structures to choose among alternative courses of action. For example,suppose the passing grade on exam is 60. The pseudo code statement

    If students grade is greater than or equal to 60

    Print Passed

    Determines whether the condition "students" grade is greater than or equal to 60 is true or false.If the condition is true, then "Passed" If the condition is false the print statement is ignored.Example as followsIf single selection structure activity diagram

    posted by Carlos @ 1:29 AM

    if/else selection structureThe ifselection structure performs an indicated action only when the condition is true otherwisethe action is skipped. The if/elseselection structure allows the programmer to specify an actionto perform when the condition is true and a different action to perform when the condition isfalse. For example, the pseudo code statement.

  • 8/10/2019 c Program Full

    47/132

    If students grade is greater than or equal to 60Print Passed

    else

    Print Failed

    Print Passed if the student's grade is greater than or equal to 60, but prints Failed if thestudent's grade is less than 60. In either case, after printing occurs. the next pseudo codestatement in sequence is performed.

    Example as followsif/else double selection structure activity diagram

    posted by Carlos @ 1:28 AM

    switch Multiple Selection StructureOccasionally, an algorithm will contain a series of decision in which a variable or expression is

    tested separately for each of the constant integral values it can assume and different actions aretaken. C++ provides the switch multiple selection structure to handle such decision making. Theswitch structure consists of a series of case labels and an optional default case

    Example as followsSwitc selection structure activity diagram.

  • 8/10/2019 c Program Full

    48/132

    posted by Carlos @ 1:27 AM

    while Repetition StructureA repetition structure allows the programmer to specify that a program should repeat an actionwhile some condition remains true. The pseudo code statement

    While there are more items on my shopping list

    Purchase next item and cross it off my list

    Describes the repetition that occurs during a shopping trip. The condition there are more items onmy shopping list is either true or false. if it is true, then the action purchase next item and cross itoff list is performed. This action will be performed repeatedly while the condition remains true.Example as followswhile repetition structure activity diagram

    posted by Carlos @ 1:26 AM

    for Repetition Structure

  • 8/10/2019 c Program Full

    49/132

    The general format of theforstructure is

    for ( initialization; loopContinuationCondition; increment)

    Statement

    Where the initialization expression initializes the loop control variable, loopContinuation is thecondition that determines whether the loop should continue executing, and increment incrementsthe control variable. In most cases, the for structure can be represented by an equivalent whilestructure, as follows:

    Initialization;

    while ( loop Continuation Condition) {

    statement

    increment;

    }Example as follows

    for repetition structure activity diagram

    posted by Carlos @ 1:25 AM

    do/while Repetition StructureThe do/whilerepetition structure is similar to the while structure. In thewhilestructure, the loopcontinuation condition test occurs at the beginning of the loop before the body of the loopexecutes. The do/whilestructure tests the loop continuation condition after the loop executestherefore, the loop body executes at least once. When a do/whileterminates, execution continueswith the statement after the while clause. Note that it is not necessary to use braces inthe do/whilestructure if there is only one statement in the body. Howeve, most programmersinclude the braces to avoid confusion between the while and do/while structures. For example

    while ( condition)

    Normally is regarded as the header to a while structure. A do/while with no braces around thesingle statement body appears as

    dostatementwhile ( condition );

    which can be confusing. The line while (condition); might be misinterpreted by the reader as a

  • 8/10/2019 c Program Full

    50/132

    while structure containing an empty statement. Thus, the do/while with one statement is oftenwritten as follows to avoid confusion;

    do {statement

    } while (condition);Example as followsdo/while repetition structure activity diagram

    posted by Carlos @ 1:24 AM

    CONTROL STRUCTURES QUIZProblem Task: Write a program to get the marks obtained from a subject by a student andcalculate the avarage grade for that particular subject?

    Here is a piece of pheudocode to help you with your answer

    If student's grade is greater than or equal to 90Print "A"else

    If student's grade is greater than or equal to 80Print "B"else

    If student's grade is greater than or equal to 70Print "C"else

    If student's grade is greater than or equal to 60Print "D"else

    Print "F"

    What does this pointer point to ? what are its application?

  • 8/10/2019 c Program Full

    51/132

    Every object in C++ has access to its own address through an important pointercalled thispointer. Thethispointer is an implicit parameter to all member functions. Therefore,inside a member function, this may be used to refer to the invoking object.Friend functions do not have a thispointer, because friends are not members of a class. Onlymember functions have a thispointer.

    Let us try the following example to understand the concept of this pointer:

    #include

    using namespace std;

    class Box{

    public:// Constructor definitionBox(double l=2.0, double b=2.0, double h=2.0){

    cout

  • 8/10/2019 c Program Full

    52/132

    {cout

  • 8/10/2019 c Program Full

    53/132

    Remember that the values those are Passed to the Functions will never effect the Actual Values

    those are Stored into the variables.

    2) Call By Reference :-When a function is called by the reference then the values those arepassed in the calling functions are affected when they are passed by Reference Means they

    change their value when they passed by the References. In the Call by Reference we pass the

    Address of the variables whose Arguments are also Send. So that when we use the Reference

    then, we pass the Address the Variables.

    When we pass the Address of variables to the Arguments then a Function may effect on the

    Variables. Means When a Function will Change the Values then the values of Variables gets

    Automatically Changed. And When a Function performs Some Operation on the Passed values,then this will also effect on the Actual Values.

  • 8/10/2019 c Program Full

    54/132

    Multiple Inheritances?

    Multiple Inheritance in C++

    Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes.

    The constructors of inherited classes are called in the same order in which they are inherited. For

    example, in the following program, Bs constructor is called before As constructor.

    #include

    using namespace std;

    class A

  • 8/10/2019 c Program Full

    55/132

    {

    public:

    A() { cout

  • 8/10/2019 c Program Full

    56/132

    For example, consider the following program.

    #include

    using namespace std;

    class Person {

    // Data members of person

    public:

    Person(int x) { cout

  • 8/10/2019 c Program Full

    57/132

    class TA : public Faculty, public Student {

    public:

    TA(int x):Student(x), Faculty(x) {

    cout

  • 8/10/2019 c Program Full

    58/132

    };

    class TA : public Faculty, public Student {

    public:

    TA(int x):Student(x), Faculty(x) {

    cout

  • 8/10/2019 c Program Full

    59/132

    Student(int x):Person(x) {

    cout

  • 8/10/2019 c Program Full

    60/132

    class C: public A

    {

    public:

    C() { setX(20); }

    };

    class D: public B, public C {

    };

    int main()

    {

    D d;

    d.print();

    return 0;}

    Question 2

    #include

    using namespace std;

    class A

    {

    int x;

    public:

    A(int i) { x = i; }void print() { cout

  • 8/10/2019 c Program Full

    61/132

    class D: public B, public C {

    };

    int main()

    {

    D d;

    d.print();

    return 0;

    }

    What is a friend function? What are its merits and demerits of using a friend function?

    A friend function of a class is defined outside that class' scope but it has the right to access allprivate and protected members of the class. Even though the prototypes for friend functionsappear 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 friendas follows:

    class Box{

    double width;public:

    double length;

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

    };

    To declare all member functions of class ClassTwo as friends of class ClassOne, place afollowing declaration in the definition of class ClassOne:

    friend class ClassTwo;

    Consider the following program:

    #include

    using namespace std;

    class Box{

    double width;public:

  • 8/10/2019 c Program Full

    62/132

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

    };

    // Member function definition

    void Box::setWidth( double wid ){

    width = wid;}

    // Note: printWidth() is not a member function of any class.void printWidth( Box box ){

    /* Because printWidth() is a friend of Box, it candirectly access any member of this class */

    cout

  • 8/10/2019 c Program Full

    63/132

    The major disadvantage of friend functions is that they require an extra line of code when youwant dynamic binding. To get the effect of a virtual friend, the friend function should call ahidden (usually protected) virtual member function. This is called the Virtual Friend FunctionIdiom. For example:

    class Base {public:

    friend void f(Base& b);...

    protected:virtual void do_f();...

    };

    inline void f(Base& b){

    b.do_f();}

    class Derived : public Base {public:

    ...protected:

    virtual void do_f(); // "Override" the behavior of f(Base& b)...

    };

    void userCode(Base& b){

    f(b);}

    The statement f(b) in userCode(Base&) will invoke b.do_f(), which is virtual. This meansthat Derived::do_f() will get control if b is actually a object of class Derived. Notethat Derivedoverrides the behavior of the protected virtual member function do_f(); itdoes nothave its own variation of the friend function, f(Base&).

    Difference between function prototyping and function overloading?

    In C++ all functions must be declared before they are used. This is accomplished using functionprototype. Prototypes enable complier to provide stronger type checking. When prototype isused, the compiler can find and report any illegal type conversions between the type ofarguments used to call a function and the type definition of its parameters. It can also find thedifference between the no of arguments used to call a function and the number of parameters in

  • 8/10/2019 c Program Full

    64/132

    the function. Thus function prototypes help us trap bugs before they occur. In addition, they helpverify that your program is working correctly by not allowing functions to be called withmismatched arguments.

    A general function prototype looks like following:

    return_type func_name(type param_name1, type param_name2, ,type param_nameN);The type indicates data type. parameter names are optional in prototype.

    Following program illustrates the value of function parameters:

    void sqr_it(int *i); //prototype of function sqr_itint main(){

    int num;num = 10;sqr_it(num); //type mismatch

    return 0;}

    void sqr_it(int *i){

    *i = *i * *i;}Since sqr_it() has pointer to integer as its parameter, the program throws an error when we passan integer to it.

    C++ function overloading programs

    Function overloading in C++: C++ program for function overloading. Function overloading

    means two or more functions can have the same name but either the number of arguments or the

    data type of arguments has to be different. Return type has no role because function will return a

    value when it is called and at compile time compiler will not be able to determine which function

    to call. In the first example in our code we make two functions one for adding two integers and

    other for adding two floats but they have same name and in the second program we make two

    functions with identical names but pass them different number of arguments. Function

    overloading is also known as compile time polymorphism.

    C++ programming code

    #include

    using namespace std;

    /* Function arguments are of different data type */

  • 8/10/2019 c Program Full

    65/132

    long add(long, long);float add(float, float);

    int main(){

    long a, b, x;float c, d, y;

    cout > a >> b;

    x = add(a, b);

    cout d;

    y = add(c, d);

    cout

  • 8/10/2019 c Program Full

    66/132

    code of functions is same except data type, C++ provides a solution to this problem we can

    create a single function for different data types which reduces code size which is via templates.

    C++ programming code for function overloading

    #include

    using namespace std;

    /* Number of arguments are different */

    void display(char []); // print the string passed as argumentvoid display(char [], char []);

    int main(){

    char first[] = "C programming";

    char second[] = "C++ programming";

    display(first);display(first, second);

    return 0;}

    void display(char s[]){

    cout

  • 8/10/2019 c Program Full

    67/132

    Opening a file using constructor

    This involves two steps

    1. Create file stream subject to manage the stream using the appropriate class. That is the class

    ofstream is used to create the output stream and the class ifstream to create the input stream.

    2. Initialize the file object with the desired filename.

    Syntax:

    Ofstream object(file_name);

    Example:

    Ofstream obj(sample.doc)

    This creates obj1 as an ofstream that manages the output stream.

    #include stream.h

    #include string.hVoid main()

    {

    char str[]=ssi computer center;

    ofstream outfile(sample.doc);

    for(int j=0;jSyntax:

    Ifstream object (file_name);

    Example:

    Ifstream obj(sample.doc)

    This creates obj1 as an ifstream that manages the input stream.

    #include fstream.h

    void main()

    {

    char ch;

    ifstream in(sample.txt);

    while(!in.eof())

    {

    in.get(ch);

    cout

  • 8/10/2019 c Program Full

    68/132

    const int MAX=80;

    char buffer[MAX];

    ifstream infile(sample.txt);

    while(!infile.eof())

    {

    infile.getline(buffer, MAX);

    cout

  • 8/10/2019 c Program Full

    69/132

    }

    // if successful creating/opening the file

    else

    {

    cout

  • 8/10/2019 c Program Full

    70/132

    Standard Template Library

    STL The C++ STL (Standard Template Library) is a powerful set of C++ template classes to

    provide general-purpose templatized classes and functions that implement many popular and

    commonly used algorithms and data structures like vectors, lists, queues, and stacks. The STL

    is a set of abstract data-types, functions, and algorithms designed to handle user-specified data-

    types The Standard Template Library is the idea of generic programming o The implementation

    of algorithms or data structures without being dependent on the type of data being handled

    Subject Teacher: Shubhashree Savant Page 23 The STL is a generic library, meaning that its

    components are heavily parameterized: o almost every component in the STL is a template STL

    is divided into three parts namely containers, algorithms, and iterators o All these three parts can

    be used for different programming problems At the core of the C++ Standard Template Library

    are following three wellstructured components: Component Description Containers Containersare used to manage collections of objects of a certain kind. There are several different types of

    containers like deque, list, vector, map etc. Algorithms Algorithms act on containers. They

    provide the means by which you will perform initialization, sorting, searching, and transforming

    of the contents of containers. Iterators Iterators are used to step through the elements of

    collections of objects. These collections may be containers or subsets of containers.

    Hope you already understand the concept of C++ Template which we already have discussed inone of the chapters. The C++ STL (Standard Template Library) is a powerful set of C++template classes to provides general-purpose templatized classes and functions that implementmany popular and commonly used algorithms and data structures like vectors, lists, queues, andstacks.

    At the core of the C++ Standard Template Library are following three well-structuredcomponents:

    Component Description

    ContainersContainers are used to manage collections of objects of acertain kind. There are several different types of containerslike deque, list, vector, map etc.

    AlgorithmsAlgorithms act on containers. They provide the means bywhich you will perform initialization, sorting, searching,and transforming of the contents of containers.

    IteratorsIterators are used to step through the elements ofcollections of objects. These collections may be containersor subsets of containers.

  • 8/10/2019 c Program Full

    71/132

    We will discuss about all the three C++ STL components in next chapter while discussing C++Standard Library. For now, keep in mind that all the three components have a rich set of pre-defined functions which help us in doing complicated tasks in very easy fashion.

    Let us take the following program demonstrates the vector container (a C++ Standard Template)

    which is similar to an array with an exception that it automatically handles its own storagerequirements in case it grows:

    #include #include using namespace std;

    int main(){

    // create a vector to store intvector vec;

    int i;

    // display the original size of veccout

  • 8/10/2019 c Program Full

    72/132

    vector size = 0extended vector size = 5value of vec [0] = 0value of vec [1] = 1value of vec [2] = 2

    value of vec [3] = 3value of vec [4] = 4value of v = 0value of v = 1value of v = 2value of v = 3value of v = 4

    Here are following points to be noted related to various functions we used in the above example:

    The push_back( ) member function inserts value at the end of the vector, expanding its

    size as needed.

    The size( ) function displays the size of the vector.

    The function begin( ) returns an iterator to the start of the vector.

    The function end( ) returns an iterator to the end of the vector.

    Function Template

    Templates are the foundation of generic programming, which involves writing code in a way thatis independent of any particular type.

    A template is a blueprint or formula for creating a generic class or a function. The librarycontainers 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 .

    You can use templates to define functions as well as classes, let us see how do they work:

    Function Template:

    The general form of a template function definition is shown here:

    template ret-type func-name(parameter list)

  • 8/10/2019 c Program Full

    73/132

    {// body of function

    }

    Here, type is a placeholder name for a data type used by the function. This name can be used

    within the function definition.

    The following is the example of a function template that returns the maximum of two values:

    #include #include

    using namespace std;

    template inline T const& Max (T const& a, T const& b)

    {return a < b ? b:a;

    }int main (){

    int i = 39;int j = 20;cout

  • 8/10/2019 c Program Full

    74/132

    Just as we can define function templates, we can also define class templates. The general form ofa generic class declaration is shown here:

    template class class-name {.

    .

    .}

    Here, type is the placeholder type name, which will be specified when a class is instantiated.You can define more than one generic data type by using a comma-separated list.

    Following is the example to define class Stack and implement generic methods to push andpop the elements from the stack:

    #include #include

    #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 (){

  • 8/10/2019 c Program Full

    75/132

    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

  • 8/10/2019 c Program Full

    76/132

    [This section corresponds to K&R Sec. 7.5]

    How will we specify that we want to access a particular data file? It would theoretically bepossible to mention the name of a file each time it was desired to read from or write to it. Butsuch an approach would have a number of drawbacks. Instead, the usual approach (and the one

    taken in C's stdio library) is that you mention the name of the file once, at the time you openit.Thereafter, you use some little token--in this case, thefile pointer--which keeps track (both foryour sake and the library's) of which file you're talking about. Whenever you want to read fromor write to one of the files you're working with, you identify that file by using its file pointer(that is, the file pointer you obtained when you opened the file). As we'll see, you store filepointers in variables just as you store any other data you manipulate, so it is possible to haveseveral files open, as long as you use distinct variables to store the file pointers.

    You declare a variable to store a file pointer like this:

    FILE *fp;

    The type FILE is predefined for you by . It is a data structure which holds theinformation the standard I/O library needs to keep track of the file for you. For historical reasons,you declare a variable which is a pointer to this FILE type. The name of the variable can (as forany variable) be anything you choose; it is traditional to use the letters fp in the variable name(since we're talking about a file pointer). If you were reading from two files at once you'dprobably use two file pointers:

    FILE *fp1, *fp2;If you were reading from one file and writing to another you might declare and input file pointerand an output file pointer:

    FILE *ifp, *ofp;

    Like any pointer variable, a file pointer isn't any good until it's initialized to point to something.(Actually, no variable of any type is much good until you've initialized it.) To actually open afile, and receive the ``token'' which you'll store in your file pointer variable, youcall fopen. fopen accepts a file name (as a string) and a modevalue indicating among otherthings whether you intend to read or write this file. (The mode variable is also a string.) To openthe file input.dat for reading you might call

    ifp = fopen("input.dat", "r");The mode string "r" indicates reading. Mode "w" indicates writing, so we couldopen output.dat for output like this:

    ofp = fopen("output.dat", "w");The other values for the mode string are less frequently used. The third major mode is "a" forappend. (If you use "w" to write to a file which already exists, its old contents will be discarded.)You may also add a +character to the mode string to indicate that you want to both read andwrite, or a b character to indicate that you want to do ``binary'' (as opposed to text) I/O.

    One thing to beware of when opening files is that it's an operation which may fail. The requestedfile might not exist, or it might be protected against reading or writing. (These possibilities oughtto be obvious, but it's easy to forget them.) fopen returns a null pointer if it can't open the

  • 8/10/2019 c Program Full

    77/132

    requested file, and it's important to check for this case before going off and using fopen's returnvalue as a file pointer. Every call to fopen will typically be followed with a test, like this:

    ifp = fopen("input.dat", "r");if(ifp == NULL)

    {printf("can't open file\n");exit or return}

    If fopen returns a null pointer, and you store it in your file pointer variable and go off and try todo I/O with it, your program will typically crash.

    It's common to collapse the call to fopen and the assignment in with the test:

    if((ifp = fopen("input.dat", "r")) == NULL){

    printf("can't open file\n");exit or return}

    You don't have to write these ``collapsed'' tests if you're not comfortable with them, but you'll

    see them in other people's code, so you should be able to read them

    Differnce between multiple and multilevel inheriatnace?

    Multilevel Inheritance

    When a class is derived form another derived class is called multilevel inheritance. In the

    following figure the class A serves as a base class for the derived class B, which in turn serves as

    a base class for the derived class C/ the class B is known as intermediate base class since it

    provides a link for the inheritance between A and C. the chain ABC is known as inheritance

    path.

    class A{}; //Base Class

    class B: public A{}; // B derived from A

    class C: public B{}; // C derived from B

  • 8/10/2019 c Program Full

    78/132

    Example:

    #include

    #include

    class Student //Base Class

    {protected:

    int rno;

    public:

    void get_number(int);

    void put_number(void);

    };

    void Student::get_number(int a){ rno = a; }

    void Student::put_number(void)

    {

    cout

  • 8/10/2019 c Program Full

    79/132

    void put_marks(void);

    };

    void Test::get_marks(int x, int y)

    {

    sub1 = x;

    sub2 = y;

    }

    void Test::put_marks(void)

    {

    cout

  • 8/10/2019 c Program Full

    80/132

    .

    Multiple Inheritance in C++

    Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes.

    The constructors of inherited classes are called in the same order in which they are inherited. For

    example, in the following program, Bs constructor is called before As constructor.

    #include

    using namespace std;

    class A

    {

    public:

    A() { cout

  • 8/10/2019 c Program Full

    81/132

    example, in the following diagram, the TA class gets two copies of all attributes of Person class,

    this causes ambiguities.

    For example, consider the following program.

    #include

    using namespace std;

    class Person {

    // Data members of person

    public:

    Person(int x) { cout

  • 8/10/2019 c Program Full

    82/132

    };

    class TA : public Faculty, public Student {

    public:

    TA(int x):Student(x), Faculty(x) {

    cout

  • 8/10/2019 c Program Full

    83/132

    Student(int x):Person(x) {

    cout

  • 8/10/2019 c Program Full

    84/132

    };

    class Student : virtual public Person {

    public:

    Student(int x):Person(x) {

    cout

  • 8/10/2019 c Program Full

    85/132

    };

    /* class C is multiple derived from its superclass A and B */class C:public A, public B

    {};

    int main(){

    C c;c.show();

    }

    Ambiguous call:

    For the above sample program, c.show() is ambiguousto get resolved among candidatefunctionsB::show() and A::show()

    Solution to ambiguous calls in multiple inheritance:

    Use scope resolution operator to explicitly specify which base class's member function is to beinvoked.

    Like, c.A::show();

    What is a copy constructor & when it is invocked? Wap with a class Abc and one integer

    data type member?overload the copy constructor and assignment operator for the class? A copy constructor is a member function which initializes an object using another object of thesame class. A copy constructor has the following general function prototype:

    ClassName (const ClassName &old_obj);

    Following is a simple example of copy constructor.

    #include

    using namespace std;

    class Point{private:

    int x, y;public:

    Point(int x1, int y1) { x = x1; y = y1; }

  • 8/10/2019 c Program Full

    86/132

    // Copy constructorPoint(const Point &p2) {x = p2.x; y = p2.y; }

    int getX() { return x; }

    int getY() { return y; }};

    int main(){

    Point p1(10, 15); // Normal constructor is called herePoint p2 = p1; // Copy constructor is called here

    // Let us access values assigned by constructorscout

  • 8/10/2019 c Program Full

    87/132

    Copy constructor vs Assignment OperatorWhich of the following two statements call copy constructor and which one calls assignmentoperator?

    MyClass t1, t2;

    MyClass t3 = t1; // ----> (1)t2 = t1; // -----> (2)

    Copy constructor is called when a new object is created from an existing object, as a copy of theexisting object. Assignment operator is called when an already initialized object is assigned anew value from another existing object. In the above example (1) calls copy constrictor and (2)calls assignment operator. See this for more details.

    Although using the assignment operator is fairly straightforward, correctly imple