c++ i mportant

Upload: trhalageri

Post on 08-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 c++ i mportant

    1/36

    Object oriented programming with C++

    1(a). What is object oriented programming? Enumerate important differences

    between object oriented and procedure oriented programming

    OOP has data as a critical component in the program development. It does not letthe data flow freely around the systems. It ties data more firmly to the functions thatoperate on it and prevents it from accidental change due to external functions. OOPpermits us to analyze a problem into a number of items known as objects and thenassembles data and functions around these items. The basic objective of OOP is to treatdata and the program as individual objects.

    Following are the important characteristics of object oriented programming:(1) OOP pays more importance to data than to function.(2) Programs are divided into classes and their member functions.

    (3) New data items and functions can be comfortably added whenever essential.(4) Data is private and prevented from accessing external functions/(5) Objects can communicate with each other through functions.

    Procedural Programming(1) In procedural programming languages such a FORTRAN and COBOL, programs

    are divided into a number of segments known as subprograms. Thus it focuses onfunctions apart from data. Here the data is not fully protected.

    (2) The control of program is transferred using statements.(3) Data is global and all the subprograms share the same data.(4) The programs are divided into multiple submodules and procedures. Each

    procedure has to perform different tasks..(5) These languages are used for developing medium size applications

    1 (b) Explain the terms:

    (i) Abstraction :

    Data abstraction directs to the procedure of representing essential features without

    including the background details. Classes use the theory of abstraction and are defined as a

    list of abstract properties such as size, cost, height and few functions to operate on these

    properties. Data abstraction is the procedure of identifying properties and methods related

    to a specific entity as applicable to the application.

    (ii) Encapsulation:

    The packing of data and functions into a single component is known as

    encapsulation. The data is not accessible by outside functions. Only those functions that are

    able to access the data are defined within the class. These functions prepare the interface

  • 8/7/2019 c++ i mportant

    2/36

    between the objects data and the program. With encapsulation data hiding can be

    accomplished.

    (iii) Polymorphism :

    Polymorphism allows the same function to act differently in different classes.

    It is an important feature of OOP concept and has the ability to take more than one form.

    Polymorphism accomplishes an important part in allowing objects of different classes to

    share the same external interface.

    (iv) Inheritance

    Inheritance is the method by which objects of one class get the properties of objects of another class. In object oriented programming, inheritance provides thethought of reusability. The programmer can be add new properties to the existingclass without changing it. This can be achieved by deriving a new class from theexisting one. The new class will possess features of both the classes. The actualPower of inheritance is that it permits the programmer to reuse a class that is close towhat he wants.

    (v) message passing Object oriented programming includes objects which communicate with each

    other. Programming with these objects should be followed in steps shown below:(1) Declaring classes that define objects and their actions.(2) Declaring objects from classes(3) Implementing relation between objects.

    (vi) Object Objects are primary run-time entities in an object oriented programming.

    They may stand for a thing that has specific application for example, a spot, a person,any data related to program, including user defined data types. Programming issuesare analyzed in terms of object and the type of transmission between them. Everyobject has its own properties or features. An object is a specimen of a class.

    2. (a) Give the classification of data types used in C++ with at least one example for each data type.

    C++ data types can be classified in the following categories:(a) Basic data type (b) Derived type

    (c) User defined type (d) Void data type(I) Basic data type:(i) Integer Eg; int c,(ii) Float Eg: float a, b, c;(iii) Char Eg: char a;

    (II) Derived data type:(i) Pointers Eg. int *x; float *f; char *y;

  • 8/7/2019 c++ i mportant

    3/36

    (ii) FunctionsEg : main()

    {funcA();.

    funcB();.}

    funcA ( ){statements;}funcB( ){statements;}

    (iii) ArraysEg; int b[4];

    int b[4] = { 2,4,3,7};

    (III) User defined data type(i) Structures and classes

    Eg: sturct name{

    char fname[];phone [ ]:int age, height;

    } n;

    class circle{

    int radius;int area ( );

    }(ii) Union

    Eg: union abc{

    int k;float j;

    }; A;(iii) Enumerated Data type

    Eg: enum logical { false, true}enum components { solid, liquid, gas}

  • 8/7/2019 c++ i mportant

    4/36

    (b). State the significance of function prototype and give the syntax to declare afunction

    A prototype statement helps the compiler to check the return andargument types of the function. A function prototype declaration consists of thefunction return type, name, and arguments list. It tells the compiler (a) the name of

    the function, (b) the type of value returned (c) the type and number of arguments.When the programmer defines the function, the definition of function must be like itsprototype declaration. If the programmer makes a mistake, the compiler flags anerror message. The function prototype declaration statement is always terminatedwith semicolon.Syntax: return_type function_name ( arg1, arg 2);

    Eg: void main(){

    float sum (float, int); //function prototypefloat x,y=2.4;int z=5;

    x=sum(y,z);}float sum (float j, int k){

    return (j +k);}

    (c). Write a C++ program to create a multiplication table for the given range.#include void main( )

    {int i ,x, mul=0;coutx;for (i=1; i

  • 8/7/2019 c++ i mportant

    5/36

    Eg:#include

    void main( ){int j;

    for (j=1;j

  • 8/7/2019 c++ i mportant

    6/36

    } while(x>y;change(x,y);cout

  • 8/7/2019 c++ i mportant

    7/36

    (2) Pass by address#include void main( )

    { int x,y;void change (int *, int*);

    cout> x>>y:change(&x, &y);cout

  • 8/7/2019 c++ i mportant

    8/36

    4. (a) Explain enumerated data types: Demonstrate the usage of enumerationconstants

    The enum is a keyword. It is used for declaring enumeration data types. Theprogrammer can declare new data type and define the variables of these data typesthat can hold.

    The syntax for enumerated data typeenum variable_name{ variable1,variable2, )Eg:

    # include void main( ){

    enum day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}day1, day2, day3, day4, day5, day6, day7;

    day1=Monday;day2=Tuesday;day3=Wednesday ;

    day4=Thursday;day5=Friday;day6=Saturday;day7=Sunday;cout

  • 8/7/2019 c++ i mportant

    9/36

    using inline function needs more memory space since the inline functions are copiedat every point where the function is invoked.Syntax: inline function_name{

    statement1;

    statement2;}when the function is having more number of statements, then it is not advisible to use

    inline function.

    (c). Differentiate among structures, unions and classes .

    Limitations with structures and unions

    (a) Only variables of different data types can be declared in the structure as member,

    functions are not allowed as members.

    (b) Direct access to data members is possible. It is because by default all the member variables are public. Hence, security to data or data hiding is not provided.

    (c) The struct data type is not treated as built in type i.e., use of struct keyword is

    necessary to declare objects.

    (d) The member variables cannot be initialized inside the structure.

    Class:

    The class declaration is same as structure declaration. The member variables and

    functions are divided in two sections i.e. private and public. The private and public

    keywords are terminated by colon(:), the object cannot directly access the member

    variables and functions declared in private section but it can access the data member

    variables and functions declared in public section. The private members of a class can

    only be accessed by public member function of the same class.

    5. Give the syntax of complex data types? Write a function that compute and returns

    the cojplex power taking the ac voltage and current in complex form as arguments.

    6.What are default arguments? Write a function called convTempr that receives thetemperature in centigrade and returns the temperature in Fahrenheit using the relation

    TF = (1.8 x T C +32). Use a default value of 25 degree Celsius for T C. Write a main()

    function that gets the value of centigrade from the user to test the program.

  • 8/7/2019 c++ i mportant

    10/36

    Solution: Default parameters are the values of specified parameters to be used in case

    they are not passed.

    include

    double convTemp(float c=25.0);

    int main() {

    float centigrade;

    double answer;

    char yorn;

    coutcentigrade;

    coutyoun;

    if(yorn==y)

    {coutcentigrade;

    answer=convtemp(float centigrade);

    }

    else

    { answer=convtemp(float 25.0);}

    cot

  • 8/7/2019 c++ i mportant

    11/36

    -------------------------------------------------------------------------------------------------------

    -------------------------------------------------------------------------------------------------------

    II IA portions

    (a) With the help of a general representation of CLASS, explain the terms class,

    private, public, data members and member functions. Give example

    class

    {

    private:

    declaration of variables;

    Prototype declaration of function;

    Public:Declaration of variables;

    Prototype declaration of function;

    };

    The class is used to pack data and function together. The class has a mechanism to

    prevent direct access to its members, which is central idea of object-oriented

    programming. The class consists of member data variables that hold data and member

    functions that operate on the member data variables of the same class.

    Private: The private keyword is used to prevent direct access to member variables or

    function by the object. The class by default produces this effect. To prevent member

    variables and functions of struct from direct access the private keyword is used. The

    private keyword is terminated by colon. The private members are not accessible by the

    object directly. To access the private members of a class, member functions of the same

    class are used. The member functions must be declared in the class in public section. An

    object can access the private members through the public member function.

    Public: The keyword public can be used to allow object to access the member variables

    of class directly like structure. The public keyword is written inside the class. It is

    terminated by colon. The member variables and functions declared followed by the

    keyword public can be accessed directly by the object.

  • 8/7/2019 c++ i mportant

    12/36

    Member functions: The member function must be declared inside the class. They can be

    defined in private or public section, inside or outside the class. The member functions

    defined inside the class are treated as inline function. If the member function is small then

    it should be defined inside the class, otherwise it should be defined outside the class. If

    function is defined outside the class, its prototype declaration must be done inside the

    class. While defining the function, scope access operator and class name should precede

    the function name.

    Member variables: The member variables must be declared inside the class. They can be

    defined in private or public section. If the variables defined in private section, then they

    should be accessed only by member functions of the class. If the variables defined in

    public section, then they can be accessed by object of that class.

    Eg:#include

    class item

    { private: // private section starts

    int codeno;

    float price;

    int qty;

    public: //public section starts

    void show( )

    { codeno=125;

    price=195;

    qty=200;

    cout

  • 8/7/2019 c++ i mportant

    13/36

    return 0;

    }

    (b).With the concept of class, write a program to calculate simple interest. Hide the

    data elements of the class using private keyword.

    #include

    class interest

    {

    private:

    float p_amount, rate, period;

    float interest, t_amount;

    public:

    void in( ){

    cout p_amount;

    coutrate;

    coutperiod;

    interest=(p_amount*period*rate)/100;

    t_amount=interest + p_amount;

    }

    void show( )

    {

    cout

  • 8/7/2019 c++ i mportant

    14/36

    r.in( );

    r.show( );

    return 0;

    }

    output

    Principle amount: 5000

    Rate of interest : 2

    Number of years: 3

    Interest : 300

    Total amount : 530

    1. (a) What is an overloaded function or function polymorphism? Explain the stepsinvolved in resolving a set of overloaded functions by taking an appropriate example .

    It is possible in C++ to use the same function name for a number of times for different intentions. Defining multiple functions with same name is known as functionoverloading of function polymorphism. Polymorphism means one function having manyforms. The overloaded function must be different in its argument list and with differentdata types. The examples of overloaded functions are given below. All the functionsdefined should be equivalent to their prototypes.Eg:

    #include int sqr (int); // function overloadingfloat sqr (float); //function overloading int sqr (int s)

    { return (s * s); }void main( ) float sqr (float j){ int a=15; float b = 2.5; { return ( j * j ); }

    cout

  • 8/7/2019 c++ i mportant

    15/36

    Eg: void setdata ( );void setdata ( int, int);void setdata (double, double);

    void main ( ){ setdata (14,25); //function call }

    It identifies the property of the argument list in the function call in terms of number of arguments data types2. Selection: This process selects the functions from the list of candidate functions whichare called with the arguments specified in the function call, provided with their number and types. The functions that are identified by the function overload resolution processare now selected for invoking with the specified argument list. The functions so selectedare called viable functions. The viable function has the following properties:(i) The number of parameters of a viable function is exactly the same as the number of arguments in the function call.(ii) The number of parameters in a viable function is more than the number of arguments

    in a function call. In such case, each additional parameter has an associated defaultargument.(iii) Best match selection: This process is to select the function that matches the functioncall the best. The function that matches best with the function call is called best viablefunction or best match function.

    (b). Write a program to swaps the contents of three variables of type int, char, float, using overloaded functions.

    #include #include

    void swap (int *a, int *b);void swap (float *a, float *b);void swap (char str1[], char str2[]);

    void main(){

    int x, y;char s[10], t[10];

    cout y;cout t;

    swap (&x,&y);cout

  • 8/7/2019 c++ i mportant

    16/36

    swap (s,t);cout

  • 8/7/2019 c++ i mportant

    17/36

    Overloading resolution is as follows:(1)Call an ordinary function that has an exact match.(2) Call a template function that could be created with an exact match.(3) try normal overloading resolution to ordinary function & call the one that matches. .

    (b). Write a C++ program to define and declare a function template to find a to the power b with a and b taking int, float and double values.

    #include#includetemplatevoid power ( T a,T b)

    { return ( pow (a,b));}int main ( ){

    p1=power (10,4);cout

  • 8/7/2019 c++ i mportant

    18/36

    private, public, data members and member functions. Give example

    class

    {

    private:declaration of variables;

    Prototype declaration of function;

    Public:

    Declaration of variables;

    Prototype declaration of function;

    };

    The class is used to pack data and function together. The class has a mechanism to

    prevent direct access to its members, which is central idea of object-oriented

    programming. The class consists of member data variables that hold data and member

    functions that operate on the member data variables of the same class.

    Private: The private keyword is used to prevent direct access to member variables or

    function by the object. The class by default produces this effect. To prevent member

    variables and functions of struct from direct access the private keyword is used. The

    private keyword is terminated by colon. The private members are not accessible by the

    object directly. To access the private members of a class, member functions of the sameclass are used. The member functions must be declared in the class in public section. An

    object can access the private members through the public member function.

    Public: The keyword public can be used to allow object to access the member variables

    of class directly like structure. The public keyword is written inside the class. It is

    terminated by colon. The member variables and functions declared followed by the

    keyword public can be accessed directly by the object.

    Member functions: The member function must be declared inside the class. They can be

    defined in private or public section, inside or outside the class. The member functions

    defined inside the class are treated as inline function. If the member function is small then

    it should be defined inside the class, otherwise it should be defined outside the class. If

    function is defined outside the class, its prototype declaration must be done inside the

  • 8/7/2019 c++ i mportant

    19/36

    class. While defining the function, scope access operator and class name should precede

    the function name.

    Member variables: The member variables must be declared inside the class. They can be

    defined in private or public section. If the variables defined in private section, then they

    should be accessed only by member functions of the class. If the variables defined in

    public section, then they can be accessed by object of that class.

    Eg:

    #include

    class item

    { private: int codeno; // private section

    starts

    float price;

    int qty;

    public: //public section starts

    void show( )

    { codeno=125; price=195;qty=200;

    cout

  • 8/7/2019 c++ i mportant

    20/36

    } c2.getdata( ); // call to member function

    c2.show( ); // call to member function

    c3.sum( c1,c2); // call to member function

    return 0;

    }

    (c). what is scope resolution operator? Where it is used?

    The scope resolution operator is the operator , which is used for defining themember function outside the class.And it is also used for differentiating between the local and global objects when bothhaving the same variable names.#include

    int x = 100;

    void main(){

    int x = 200;

    cout

  • 8/7/2019 c++ i mportant

    21/36

  • 8/7/2019 c++ i mportant

    22/36

    };int number ::c=0; //initialization of staticmember variable

    c=1c=2c=3

    Here the class nuber has one static data variable c. The count () is a member functionsincrement value of static member variable c by one when called. The three objects in themain function calls the function count(), at each call to the function count(v) the variablec gets incremented and the cout statement displays the value of variable c.

    (c).What are static member functions? Explain with the help of a suitable c++program

    The static member functions are applied to all the objects of the class.The static member functions address only the static data members of a class. But, thenon-static data members are not available to these static member functions.A static member function does not contain the this pointer. So the static member functions cannot call non-static member functions of the class. Static member functions

    can be invoked using class name. It is also possible to invoke static member functionsusing objects. When one of the objects changes the value of dat member variables, theeffect is visible to all the objects of the class.

    #include class checkObject{ private: static int num;

    public: static int totalObjects(void){ num = num + 1;

    return num;}

    void display (void){cout

  • 8/7/2019 c++ i mportant

    23/36

    class person{ private: int rollno;

    char name[20];float percentage;

    public: class date {

    private: int day;int month;int year;

    public: void setdate(int dd, int mm, int yyyy){day = dd; month = mm; year = yyyy;}void printDate(void){ cout

  • 8/7/2019 c++ i mportant

    24/36

    class. Using copy constructors, it is possible for the programmers to declare and initializeone object using reference of another object. Thus whenever a constructor is called acopy of an object is created.Eg;#include

    class num{ int n;public:num ( ) { }num (int k) {n=k;}num (num &j) //copy constructor { n=j.n; }void show (void ) {cout

  • 8/7/2019 c++ i mportant

    25/36

    A friend function cannot access the class members directly. An object namefollowed by dot operator, followed by the individual data member is specified for validaccess.

    forward declaration means when we are using twoor more classes in our program, we will have to declare the classes which we will be using before defining,

    so that while executing the compiler will be knowing how many classes are there inthe program.#include

    Class ABC; // forward declarationClass XYZ

    {int x;public:void setvalue(int i) {x=I;}friend void max(XYZ,ABC); // friend function declared and objects from both the

    classes are passed as arguments.

    };class ABC{int a;public:void setvalue(int i) {a=i;}friend void max(XYZ,ABC);};void max(XYZ m, ABC n) // friend function defined{if ( m.x >= n.a)

    cout

  • 8/7/2019 c++ i mportant

    26/36

    { int num,power,ans;public: power (int n=9,int p=3); //declaration of constructor with defaultargumentsvoid show(){

    cout

  • 8/7/2019 c++ i mportant

    27/36

    17. What are the different types of constructors? In what way these are differentfrom other member functions.

    18. Write a simple C++ program to illustrate passing and returning of objects tofunctions.

    Solution

    #include < iostream.h>Class Complex // x+iy form{ float x,y;

    public: void input(float real, float imag){x = real; y=imag;}

    friend complex sum(complex,complex);void show (complex);};complex sum(complex c1,complex c2)//function with passing and returning object

    { complex c3; //objectc3.x =c1.x + c2.x;c3.y = c1.y + c2.y;return (c3); // returning object}void complex::show(complex c){ cout

  • 8/7/2019 c++ i mportant

    28/36

    p2.display();return 0;}

    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------III IA portions

    1. (a) . What is Operator overloading? Explain the steps involved in operator overloading taking a suitable example.(10marks)

    Operator overloading is one of the most valuable concepts introduced by C++language. It is a type of polymorphism. Polymorphism permits to write multipledefinitions for functions and operators. C++ has number of standard data types like int,float, char etc. The operators +,-,* and = are used to carry operations with these datatypes. Operator overloading helps programmer to use these operators with the objects of classes. The outcome of operator overloading is that objects can be used in a naturalmanner as the variables of basic data types. Operator overloading provides the capabilityof redefine the language in which working operator can be changed.Syntax:return type operator operator_symbol (parameters)

    {statement;

    }Eg.#include class number { public: int x;

    int y;number ( ) { }//zero argument constructor.number ( int j, int k)// Two argument

    constructor { x=j; y=k;}number operator + (number D){ number T;

    T.x = x+D.x;T.y=y+D.y;

    void main ( ){number A(2,3),B(4,5),C;A.show( );B.show ( );C = A+B;C.show ( );}

    outputx=2 y=3x=4 y=5

  • 8/7/2019 c++ i mportant

    29/36

    return T; }void show ( ){ cout

  • 8/7/2019 c++ i mportant

    30/36

    {complex c;

    c.real= a.real-b.real;c.imag=-a.imag-b.real;return c;

    }};void menu(void){cout

  • 8/7/2019 c++ i mportant

    31/36

    (b). Write a note on copy constructor .The constructor can accept arguments of any data type including user defined data

    types and an object of its own class.Eg;Class num

    {private;public:num (num &);}It is possible to pass reference of object to the constructor. Such declaration is known ascopy constructor. It is used as copy constructor.When we pass an object by value into a function , a temporary copy of that object iscreated. All copy constructors require one argument, with reference to an object of thatclass. Using copy constructors, it is possible for the programmers to declare and initializeone object using reference of another object. Thus whenever a constructor is called acopy of an object is created.

    Eg;#includeclass num{ int n;public:num ( ) { }num (int k) {n=k;}num (num &j) //copy constructor { n=j.n; }void show (void ) {cout

  • 8/7/2019 c++ i mportant

    32/36

    { num = num + 1;return num;

    }void display (void){

    cout

  • 8/7/2019 c++ i mportant

    33/36

    (vi) protected members of B. : not accessible ( 6 marks).

    (c). Write a suitable program to illustrate the multilevel inheritance. The program isto create a base class called grand father and to derive it to father class which in turnis derived to son class. Select different member functions in class declaration (8 marks).

    #include #include class grandFather {

    private: char name[25];int age;public: char color[15];void getData();void display();

    };

    class father : public grandfather //derivedclass: level 1

    { class son : public father//derived class:level 2{

    private: char hobby[20];public : void input();

    void output();};void grandFather::getData(){

    coutname;coutage;coutcolor;

    }void grandFather::display(){

    cout

  • 8/7/2019 c++ i mportant

    34/36

    cin >>qualification;coutsalary;coutIQ;

    }

    Enter the salary : 25000Enter the IQ : 90Enter the Hobby : painting

    Son's information is as follows...

    Name = SharanAge = 28Color = black Qualification = BESalary = 25000IQ = 90Hobby = painting--------------------------------------*/

    4 (a) Create a class called time that has separate int member data for hours, minutes,and seconds. One constructor should initialize this data to zero, and another should

    initialize it to fixed values. Another member function should display it, inhh;mm;ss format.

    (b). What are virtual classes ? Explain with an example.

    #include #include class BC1{

    protected: int i;public: void get_i();

    void put_i();};

    class DC1 : virtual public BC1//virtual base class

    {protected: int j;public: void get_j();void put_j();

    };class DC2 : virtual public BC1 //virtualbase class{

    protected: int k;public: void get_k();

    void put_k();};

    void DC2:: get_k(){ cout

  • 8/7/2019 c++ i mportant

    35/36

    class DC3 : public DC1, public DC2{

    private: int sum;public: void print_sum();

    };

    void BC1:: get_i(){ cout

  • 8/7/2019 c++ i mportant

    36/36