CPP IMPORTANT QUESTIONS FOR ASSIGNMENTS

Document Sample
CPP  IMPORTANT QUESTIONS FOR ASSIGNMENTS Powered By Docstoc
					HW1

Question 1: How does a switch statement differ from multiway if-else statement? Think of
relative pros and cons. Give a program in support of your stated difference.

Ans 1: The switch and if-else both are selection statements and they both let you select an
alternative out of given many alternatives by testing an expression. However , there are some
differences in their operations. These are given below:

    1. The switch statement differs from the if statement in that switch can only test for
       equality whereas if can evaluate a relational or logical expression i.e multiple conditions.
    2. The switch statement selects its branches by testing the value of same variable (against a
       set of constants) whereas the if-else construction lets you use a series of expression that
       may involve unrelated variables and complex expressions.
    3. The if-else is more versatile of the two statements. For instance,     if-else can handles
       ranges whereas switch cannot. Each switch case label must be a single value.
    4. The if-else statement can handle floatin- point test also apart from handling integer and
       character test wheras a switch cannot handle floating-point test. The case of switch must
       be an integer (which includes char also).
    5. The switch case label value must be a constant. So, if two or more variables are to be
       compared, use if-else.
    6. The switch statement is more efficient choice in terms of code used in a situation that
       support the nature of switch operation (testing a value against a set of constants).


For example::

/*Program:: To input number of week‟s day (1-7) and translate to its equivalent name of the
week using switch.*/


#include<iostream.h>
Int main()
{
Int dow ;
Cout<<”Enter the number of week‟s day(1-7) :: ”;
Cin>>dow;
Switch(dow) ;
{
Case 1: cout<<”\nSUNDAY”;
        Break;

Case 2: cout<<”\nMONDAY”;
        Break;

Case 3: cout<<”\nTUESDAY”;
        Break;

Case 4: cout<<”\nWEDNESDAY”;
        Break;
Case 5: cout<<”\nTHURSDAY”;
        Break;

Case 6: cout<<”\nFRIDAY”;
        Break;

Case 7: cout<<”\nSATURDAY”;
        Break;

Default : cout<<”\nwrong no. of day”
         Break;
}

Return 0;
}


OUTPUT::

Enter no. of week‟s day(1-7) : 5

Thursday


/*Program:: To input a character and to print whether the given character is alphabet, digit or any
other character using if-else.*/


#include<iostream.h>
Int main()
{
Char ch ;
Cout<<”Enter a character :”;
Cin>>ch ;
If (((ch>=‟A‟) &&(ch<=‟Z‟)) || ((ch>=‟a‟) && (ch<=‟z‟)))
Cout<<”You entered an alphabet\n”;

Else

If(ch >=‟0‟&& ch<=‟9‟)
Cout<<”You entered a digit\n”;

Else

Cout<<”You entered a character other than alphabets and digits\n”;

Return 0;

}
OUTPUT::


Enter a character:: 7

You entered a digit



Question 2: a) In C++, can a function be called from more than one place within a
program?
            b) How does function overloading help in program development. Overload area
function to find area of rectangle, square and circle.

Ans. a) /*Program to call a function from more than one place*/

#include<iostream.h>

#include<conio.h>

class abc

{

int a,b;

public:

void getdata();

void display();

};

void abc::getdata()

{

display();

cout<<”\nEnter the values of a and b\n”;

cin>>a>>b;

}

void abc::display()

{
cout<<”\nvalue of a= “<<a<<” and b=”<<b<<”\n”;

}

void main()

{

clrscr();

abc obj;

obj.getdata();

obj.display();

getch();

}



OUTPUT

value of a=2345 and b=1277

Enter the values of a and b

100 101

value of a=100 and b=101



b) With the facility of function overloading you can have multiple functions with the same name .
using this concept of function overloading ,we can design a family of functions with one function
name but with different argument list. The function would perform different operations
depending on the argument list in the function call. The correct function to be invoked is
determined by checking the number and type of arguments but not on the function type.



/*Program to find the area of rectangle, square and circle using function overloading*/

#include<iostream.h>

#include<conio.h>

class areas

{
int l,b,s;

float r;

public:

void ar(int,int);

void ar(int);

void ar(float);

};




void area::ar(int a, int b)

{

cout<<”\nArea of rectangle=”<<a*b<<”\n”;

}




void areas::ar(int a)

{

cout<<”\nArea of square=”<<a*a<<”\n”;

}




void areas::ar(float a)

{

cout<<”\nArea of circle=”<<3.14*a*a;

}
void main()

{

clrscr();

areas obj;

cout<<”Enter the length and bredth of rectangle\n”;

cin>>l>>b;

obj.ar(l,b);

cout<<”\nEnter the side of the square\n”;

cin>>s;

obj.ar(s);

cout<<”\nEnter the radius of the circle\n”;

cin>>r;

obj.ar(r);

getch();

}



OUTPUT

Enter the length and breadth of rectangle

56

Area of the rectangle=30

Enter the side of the square

5

Area of the square=25

Enter the radius of the circle

6
Area of the circle=113.14




Question 3: The effect of a default argument can be alternatively achieved by overloading.
Discuss with an example. Can you solve the above program using default arguments?



Ans 3: Functions in c++ have an ability to define default values for arguments that are not passed
when the function call is made. Default arguments provide us the facility of using default values
if no other values are passed.



For example::

#include<iostream.h>
#include<conio.h>

Int main()
{
Float amount;

Float value(float p, int n, float r=0.15);
Void printline(char ch=‟*‟, int len=40);

Printline();

Amount = value(5000.00,5);

Cout<<”\nFinal value = “ <<amount <<”\n\n”;

Printline(„=‟);

Return 0;

}


{

Int year =1;
Float sum =p;

While(year <= n)
{
Sum =sum*(1+r);
Year= year+1;
}

Return(sum);
}

Void printline(char ch, int len)

{

For(int i=1;i<=len;i++)
Printf(“%c”,ch);
Printf(“\n”);
}
OUTPUT

*****************************************

Final value =10056.8

====================================



Question 4: Can we use the same function name for a member function of a class and an
outside function in the same program file? If yes, how are they distinguished? If no, give
reasons.



Ans 4: Yes, we can use the same function name to define a function within the class as well as
outside the class. In such case both the functions get distinguished by the arguments passed to
them.

#include<iostream.h>

#include<conio.h>

class cal

{

public:

void mul(int a,int b)

{

cout<<”Multiplication of the integers=”<<a*b;

}
void mul(float,float);

};

void cal::mul(float x,float y)

{

cout<<”\nMultiplication of floating nos=”<<x*y;

}

void main()

{

clrscr();

cal c;

c.mul(5,6);

c.mul(5.1,6.1);

getch();

}

OUTPUT

Multiplication of the integers=30

Multiplication of floating nos.=31.11



Question 5: Create a class to represent a bank account. It should include the following:

Data members:
             Name of account holder
             Account number
             Type of account
             Balance amount
Member functions:
             To initialize the data members with appropriate data
             To deposit an amount
             To withdraw an amount after checking the balance
             To display details of account holder


Ans.
#include<iostream.h>

#include<conio.h>

#include<stdio.h>

class bank

{

char name[20],ac_type[20];

long int ac_no;

float balance=10000.0,dep,wit;

void initial();

void deposit(float);

void withdraw(float);

void display();

};

void bank::initial()

{

cout<<”************************************************************\nBANK
ACCOUNT\n\n\nEnter the customer‟s name\n”;

cin>>name;

cout<<”Enter the account number\n”;

cin>>ac_no;

cout<<”\nEnter the account type\n”;

cin>>type;

}

void bank::deposit(float x)

{

cout<<”\n\nAmount deposited = “<<x;
balance +=x;

cout<<”\nUpdated account balance =”<<balance<<”\n”;

}

void bank::withdraw(float x)

{

if(x>balance)

{

cout<<”Transaction Cancelled”;

break;

}

cout<<”

cout<<”\n\nAmount withdrawn = “<<x;

balance-=x;

cout<<”\nUpdated account balance =”<<balance<<”\n”;

}

void bank::display()

{

cout<<”\n\n\n\n****************************************************\n\n”;

cout<<”Name of the account holder :: ”<<name;

cout<<”Account Number:”<<ac_no<<”\n”<<”Account Type:”<<type<<”\nBalance
Available:<<balance;

}

void main()

{
int a;

float f;

bank b;
b.initial();

cout<<”\nDo you want to \n1)deposit\n2)withdraw\n”;

cin>>a;

switch(a)

{

case 1:cout<<”\nEnter the amount to be deposited\n”;

           cin>>f;

           deposit(f);

           break;

case 2: cout<<”\nEnter the amount to be withdrawn\n”;

           cin>>f;

           withdrawn(f);

           break;

}

b.display();

getch();

}



OUTPUT



************************************************************

BANK ACCOUNT



Enter the customer‟s name

abcABC

Enter the account number
3000809677867

Enter the account type

Savings

Do you want to

1)deposit

2)withdraw

1

Enter the amount to be deposited

500.0

Amount Deposited=500.0

Updated balance=10500.0



*******************************************************



Name of the account holder:ABCabc

Account number: 3000809677867

Account Type:Savings

Balance Available:10500.0




Question 6: Design two classes named Distance1 and Distance 2 to represent length of an
object in meters and centimeters and feet and inches respectively. Write conversion routines
for converting length from meters and centimeters to feet and inches and vice versa.
Ans 6:

#include<conio.h>

#include<iostream.h>

#include<math.h>

class mcm
{

public:

int m,cm;

void enterm();

};



class feetin

{

public:

int feet,inches;



void enter()

{

cout<<"\nEnter feet : ";

cin>>feet;

cout<<"\nEnter inches : ";

cin>>inches;

}

mcm convert1()

{

mcm temp;



temp.cm=feet*30.48+inches*2.54;

temp.m=temp.cm/100;

temp.cm%=100;

return temp;
}

};

void mcm::enterm()

{

cout<<"\n\n\n\t\t***************************************\n\n\n\n\nEnter meter : ";

cin>>m;

cout<<"\nEnter centimeter : ";

cin>>cm;

}

feetin convert2(mcm a)

{

feetin temp;

temp.inches=(a.m*100+a.cm)/2.54;

temp.feet=temp.inches/12;

temp.inches%=12;



return temp;

}



void main()

{

clrscr();

feetin a;

a.enter();



mcm b=a.convert1();
cout<<"\nAFTER CONVERSION \n\nMetres : "<<b.m<<"\n\nCentimeters : "<<b.cm;



mcm c;

c.enterm();

feetin d=convert2(c);



cout<<"\nAFTER CONVERSION\n\nFeet : "<<d.feet<<"\n\nInches :"<<d.inches;

getche();

}

OUTPUT

Enter feet : 4

Enter inches : 3

AFTER CONVERSION

Meter : 1

Centimetre : 29

         *****************************************************

Enter meter : 5

Enter centimeters : 6

AFTER CONVERSION

Feet : 16

Inches : 7
HW2

PART-A

Question 1: a) How are static variables used to maintain values common to the entire class?
When do we declare the member of a class static?
b) WAP to define static data member which has the initial value of 100 to find out the sum
of the following series:
sum=1+2+3+……..+10
The summing is to be repeated five times.


Answer : a) A static variable is a variable which exist across instances of a class. Static
variables are normally used to maintain values common to the entire class. A static variable is
created for the class rather than objects. Only one copy of a static variable exists and all objects of
the class share this copy. Any type of modifications made by the object doesn‟t make any effect
for the other objects accessing that variable.

EXAMPLE::

#include<iostream.h>

#include<conio.h>

class myclass

{

    static int i;

public:

    void setInt(int n)

    {

        i = n;

    }

    int getInt()

    {

        return i;

    }
};

int myclass::i;           // Definition of myclass::i. i is still private to myclass.

int main()

{

    clrscr();

    myclass object1, object2;

    object1.setInt(10);

    cout << "object1.i: " << object1.getInt() << '\n'; // displays 10

    cout << "object2.i: " << object2.getInt() << '\n'; // also displays 10

    getch();

    return 0;

}

OUTPUT::

Object1.i:10

Object2.i:10




b)

#include<iostream.h>

#include<conio.h>

class sum

{

static int A;

int tot,a,b;

public:

void sum_series()
{

for(a=1;a<=5;a++)

    {

    tot=0;

    cout<<"\nSumming done for "<<a<<" times\n";

    for(b=1;b<11;b++)

        tot+=b;

    cout<<"\nSum total ="<<tot<<endl;

    }

}

};

int sum::A=100;

void main()

{

clrscr();

sum s;

s.sum_series();

getch();

}




OUTPUT

Summing done for 1 times

Sum total=55

Summing done for 2 times

Sum total=55
Summing done for 3 times

Sum total=55

Summing done for 4 times

Sum total=55

Summing done for 5 times

Sum total=55



Question 2: An employer plans to pay a bonus to all his employees. A bonus of 10% is to be
paid to employees with earnings at least Rs5000/- and 20% of the earning to others. The
input contains emp_id, name and earnings of an employee and the desired output is name
and bonus to be paid to the employee.
Create a class to represent an employee .It should include the following:
Data members:
Emp_id
Name
Earning
Bonus
Member Functions:
To input data
To compute bonus
To output desired information


ANSWER::

#include<iostream.h>

#include<conio.h>

class employe

{

long int emp_id;

char name[20];

float earning,bonus,emp_code;

public:

void enter_data();

void display_data();
void calculate();

};

void employe::enter_data()

{

    cout<<"Enter the name of the employee :: ";

    cin>>name;

    cout<<"\nEnter the employee code :: ";

    cin>>emp_code;

cout<<"\nEnter the income of the employee :: ";

cin>>earning;

}

void employe::calculate()

{

if(earning==5000)

bonus=0.1*earning;

else

bonus=0.2*earning;

}

void employe::display_data()

{

cout<<"\n\nName :"<<name<<endl<<"Employee
Code:"<<emp_code<<endl<<"Earnings:"<<earning<<endl<<"Bonus:"<<bonus<<endl<<"Total
income:"<<bonus+earning;

}

void main()

{

clrscr();
employe e;

e.enter_data();

e.calculate();

e.display_data();

getch();}



OUTPUT

Enter the name of the employee :: RAMESH

Enter the employee code :: 30405698

Enter the income of the employee :: 1000



Name: Swapnil

Employee code 30405698

Earnings: 1000

Bonus:200

Total income:1200




Question 3: How does the concept of friend function help in the program development?
Think of the merits and demits of friend function. Write a program implementing the usage
of friend function by taking a class student and taking attributes of student as data
members.


ANSWER :: Sometimes , private and protected members of a class need to be shared with an
outsider function. In such case , instead of making private and protected data public, access to
these data is allowed by declaring the outsider function as a friend function. Thus, still the data
privacy is maintained from the outside world , only access is permitted to friend functions.
Therefore, declaring a function as a friend is much better than declaring all the private and
protected data public.
A friend function is a non member function of class which has the right to access private
members of the class. It is declared in the scope of class either privately or publically with a
keyword friend in the beginning as follows:

                                      friend void f1(X x);

Here X is the name of the class and x is the object of class X.


MERITS OF FRIEND FUNCTION:-

- allows to even access the private data functions of the class.

- functions can be accessed without usage of functions in the class.

- allows sharing of functions b/w 2 classes.

DEMERITS OF FRIEND FUNCTION:-

- contradicts the concept of data hiding.


EXAMPLE::


#include<iostream.h>
#include<conio.h>
class sum
{
int a,b;
public:
void enter_data()
{
cout<<"Enter the two numbers\n\n";
cin>>a>>b;
}
friend void cal(sum s);
};
void cal(sum s)
{
cout<<"\nSum is :: "<<s.a+s.b;
}
void main()
{
sum x;
x.enter_data();
cal(x);
getch();
}
OUTPUT::

Enter the two numbers
33
44
Sum is :: 77



Question 4: Can we have more than one constructor in a class? If yes, explain the need for
such a situation with the help of a relevant example.


ANSWER:: Yes we can have more than one constructor in a class. Different objects can be
invoked in different ways by initializing them different values when each of the function is
invoked.

EXAMPLE::
# include <iostream.h>
# include <conio.h>
class A
{
int a,b;
public:
A()
{
cout<<"DEFAULT CONSTRUCTOR INVOKED....!!!";
}
A(int x,int y)
{
a=x;
y=b;
cout<<"\n\nPARAMETERIZED CONSTRUCTOR INVOKED.....!!!!!";
}
A(A &p)
{
a=p.a;
b=p.b;
cout<<"\n\nCOPY CONSTRUCTOR INVOKED.....!!!!";
}
};
void main()
{
clrscr();
A p;
A p1(2,3);
A p2=p1;
getch();
}
OUTPUT::
DEFAULT CONSTRUCTOR INVOKED....!!!
PARAMETERIZED CONSTRUCTOR INVOKED.....!!!!!
COPY CONSTRUCTOR INVOKED.....!!!!"



Question 5: Develop a program in C++ to prepare mark sheet of an university examination
assuming that the following items can be read from the keyboard:
Name of student
Roll no
Subject code
Subject name
Inte marks
Ext marks
Construct the program with suitable member functions for initializing and destroying the
data viz constructor, default constructor, copy constructor, destructor, static member
functions and friend function.

ANSWER ::

#include<iostream.h>

#include<conio.h>

class student

{char name[20];

int roll no;

int sub_coe;

char sub_name;

int internal;

int external;

public:

student()

{

rollno=0; z)

{

rollno=x;

internal=y;
external=z;

}

student(student&s)

{

rollno=s.rollno;

internal=s.internal;

external=s.external;

}

friend void getdata()

{

cout<<"eneter the details of the student";

cout<<"name";

cin>>name;

cout<<"rollno";

cin>>rollno;

cout<<"subjectname";

cin>>sub_name;

cout<<"sub_code";

cin>>sub_code;

cout<<"internal and external marks";

cin>>internal>>external;

}

friend void printdata()

{

cout<<"the details of the student are";

cout<<"name"<<name;
cout<<"roll no"<<rollno;

cout<<"subjectcode"<<sub_code;

cout<<"subject name"<<sub_name;

cout<<"internal marks"<<internal;

cout<<"external marks"<<external;

}



~student()//default destructor

{

}

};

void main()

{

int i;

student s[50];

cin>>n;

for(i=0;i<50;i++)

{

s.getdata();

printdata();

}

}
Question 6: Distinguish between the following two statements:
                       time T2(T1);
                       time T2=T1;

                          T1 and T2 are objects of time class.

ANSWER::

There is not much difference between these two statements . We can see that T1 and T2 are two
objects declared under the class time and the above two statements are working as the copy
constructor. Copy constructor is being called simply copying T1 to T2. The only difference in
these two statements is the way the copy constructor is invoked.

time T2(T1) is known as implicit function call and time T2(T1) is known as explicit function
call




CSE202 HW3


Question 1: a) In what order are the class constructors called when a derived class object is
created?

          b) Class D is derived from class B. The class D does not contain any data
members of its own. Does the class D require constructors? If yes, why?

ANSWER 1: a) Constructors play an important role in initialling object. . If any base class
contains a constructor with one or more arguments, then it is mandatory for the derived class to
have a constructor and pass the arguments to the base class constructor. While applying
inheritance we uasually create objects using the derived class. Thus, it makes sense for the
derived class to pass arguments to the base class constructors, the base constructor is executed
first and then the constructor in the derived class is executed.

   Since the derived class supply initial values to its base classes ,we sup[ply the initial values
that are required by all the classes together, when a derived class object is declared.

     The constructor of the derived class receives the entire list of values as its arguments and
passes them on to the base constructors in the order in which they are declared in the derived
class. The base constructors are called and executed before executing the statements in the body
of the derived constructor.
b) Yes, the class D must define a constructor because it is the responsibility of the derived class
constructor to invoke the base class constructor by passing its required arguments to it. For
example



            #include<iostream.h>
            #include<conio.h>
            class B
            {
            public:
            B() //constructor of base class or member function
            {
            cout<<”No parameter constructor is called: “<<endl;
            }
            };
            class D:public B
            {
            Int a,b;
            public:
            D(int x,int y) //
            {
            a=x; b=y;
            cout<<”Constructor with two parameter is called: “<<endl;
            }
            };
            int main()
            {
            Clrscr();
            D obj(10,15);
            Getch();
            }
            OUTPUT
            No constructor parameter is called

           Constructor with two parameter is called



Question 2: We know that a private member of a base class is not inheritable. Is it anyway
possible for the objects of a derived class to access the private members of the base class? If
yes, how? Remember the base class cannot be modified.

ANSWER 2 : A derived class does not get direct access privilege for a private member of its base
class, however, it always can access(INDIRECTLY) the private members of its base class
through an inherited function that is accessing these members.
e.g

An example:-

#include<iostream.h>

#include<conio.h>

class X

{

private:

int a;

public:

int b;

int get()

{

cout<<”Enter the value of a and b:\n “;

cin>>a>>endl>>b;

}

int put()

{

cout<<”the value of a and b is: “<<a<<endl<<b<<endl;

}

int returna()

{

return(a);

}

};

class Y:private X

{
private:

int sum;

public:

int put_data( )

{

get();

sum=b+returna();

cout<<”The sum is: “<<sum<<endl;

}

int display()

{

put();

cout<<”Sum= “<<sum;

}

};

int main()

{

clrscr();

Y obj;

obj.put_data();

obj.display1();

getch();

}

OUTPUT

Enter the value of a and b: 1 2

The value of a and b is 1 2
The sum is: 3

Sum=3



Question 3: Assume that a publishing company prints books and digital books(electronic
form-CD). Create a class named publication with data members title, price, and author’s
name. From publication class, derive two classes named book and ebook. Te book class adds
a page count data member named pcount while ebook adds data member playing time name
ptime. Each of these classes must have member function getdata( ) to read class specific data
from keyboard and displaydata( ) to output the class specific data to the computer screen.

ANSWER 3:

#include<iostream.h>

#include<conio.h>

class publication

{

public:

float price;

char title,author_name;

int getdate()

{

cout<<”Enter the price of the book: “<<endl;

cin>>price;

cout<<”Enter the title of the book and the name of the author: “<<endl;

cin>>title>>”::”>>author_name;

}



int displaydata()

{

cout<<”The price of the book is = “<<price<<endl;
cout<<”The name of the author is = “<<author_name<<endl;

cout<<”The title of the book is = “<<title<<endl;

}

};

class book:public publication

{

public:

int pcount;

int getdata()

{

cout<<”Enter the number of pages: “<<endl;

cin>>pcount;

}

int displaydata()

{

cout<<”The toatal page count is: “<<pcount<<endl;

}

};

class ebook:public book

{

public:

char ptime[20];

int getdata()

{

cout<<”Enter the time of publication: “<<endl;

cin>>ptime;
}

int displaydata()

{

cout<<”The time is: “<<ptime<<endl;

}

};

void main()

{

clrscr();

ebook obj;

obj.publication::getdata();

obj.book::getdata();

obj.publication::displaydata();

obj.book::displaydata();

obj.getdata();

obj.displaydata();

getch();

}

OUTPUT:

Enter the price of the book:475

Enter the title of the book: CHEMISTRY

Enter the author‟s name: DINESH

Enter the number of pages:512

The price of the book is:475

The title of the book is:CHEMISTRY

The author‟s name is:DINESH
Total page count is:512

Enter the time of publication: 6:30 PM

The time is: 6:30 PM



PART-B

Question 4: (a) How is polymorphism achieved at (a) compile time (b) run time?

(b) How does the concept of virtual function help in achieving polymorphism?

Illustrate your answer by giving a suitable example.

ANSWER 4: a)

    i)      Compile time Polymorphism: It means that an object is bound to its function call at
            compile time. That is the information is known to the compiler at the compile time
            and therefore, compiler is able to select the appropriate function for a particular call
            at the compile time itself. This is called Compile time polymorphism and also called
            early binding or static binding or static linking.

    ii)     Run Time Polymorphism: In this type the appropriate member function could be
            selected while the program is running. C++ supports a mechanism known as virtual
            function to achieve Run Time Polymorphism. At run time, the appropriate version of
            the function is invoked if the class object is known. Since the function is linked with
            a particular class much later after the compilation, this process is termed as late
            binding. It is also known as dynamic binding because the selection of the appropriate
            function is done dynamically at run time.



b) Virtual Functions are resolved during run-time or dynamic binding. Virtual functions are also
simple member functions. The vital reason for having a virtual function is to implement a
different functionality in the derived class.

For example: a Make function in a class Vehicle may have to make a Vehicle with red color. A
class called FourWheeler, derived or inherited from Vehicle, may have to use a blue background
and 4 tires as wheels. For this scenario, the Make function for FourWheeler should now have a
different functionality from the one at the class called Vehicle. This concept is called Virtual
Function.

For example, the general syntax to declare a Virtual Function uses:

class classname //This denotes the base class of C++ virtual function
{
public:
virtual void memberfunctionname() //This denotes the C++ virtual function
{
.............
............
}
};

FOR EXAMPLE::

class Vehicle //This denotes the base class of C++ virtual function
{
public:
virtual void Make() //This denotes the C++ virtual function
{
cout <<"Member function of Base Class Vehicle Accessed"<<endl;
}
};



class FourWheeler : public Vehicle
{
public:
void Make()
{
cout<<"Virtual Member function of Derived class FourWheeler Accessed"<<endl;
}
};



void main()
{
Vehicle *a, *b;
a = new Vehicle();
a->Make();
b = new FourWheeler();
b->Make();
}



Question 5: When do we make a virtual function “pure”? What are the implications of
making a function a pure virtual function?

ANSWER 5: A virtual function that is initialized to zero (0) is referred to as pure virtual
function.It has no body and hence also known as do-nothing or the dummy function.
Example: virtual void show()=0;
We should use pure virtual function if we do not want to instantiate a class but make it act as a
base class for all the classes that derive from it.An important thing
to note about pure virtual functions is that these functions must be overridden in all the derived
classes otherwise the compile would flag out an error.


Sample program:

class alpha
{
public:virtual void show()=0; //pure virtual function
};
class beta:public alpha
{
public:void show() //overriding
     {
     cout<<"OOP in C++";
     }
};
void main()
{
alpha *p;
beta b;
p=&b;
p->show();
}

Output: OOP in C++



Question 6: Develop an object oriented program in C++ to read the following information
from the keyword in which the base class consists of employee name, code and designation,
and the derived class containing the data members, viz. years of experience and age.

            a) Employee name
            b) Employee code
            c) Designation
            d) Years of experience
            e) Age
        Design a virtual base class for the item employee name and code.



ANSWER 6:

#include<iostream.h>
#include<conio.h>

class employee

{

protected:

int emp_code;

public:

char emp_name;

int designation;

void read()

{

cout<<”Enter the name of the employee: “<<endl;

cin>>emp_name;

cout<<”Enter the employee code: “<<endl;

cin>>emp_code;

cout<<”Enter the house number of the employee: “<<endl;

cin>>designation;

}

void show()

{

cout<<”The name of the employee is: “<<emp_name<<endl;

cout<<”The employee code is: “<<emp_code<<endl;

cout<<” The house number of the employee is #”<<designation<<”LAJPAT NAGAR” <<endl;

}

};

class detail:public virtual employee

{
public:

int exp;

int age;

void put()

{

cout<<”Enter the experience of the employee: “<<endl;

cin>>exp;

cout<<”Enter the age of the employee: “<<endl;

cin>>age;

}

void display()

{

cout<<”The experience of the employee is: “<<exp<<endl;

cout<<”The age of the employee is: “<<age<<endl;

}

};

void main()

{

Clrscr();

detail d;

d.read();

d.put();

d.show();

d.display();

getch();

}
OUTPUT::

Enter the name of the employee: RAMESH

Enter the code of the employee: 1234

Enter the house number of the employee:64

Enter the experience of the employee:12

Enter the age of the employee:42

The name of the employee is: RAMESH

The code of the employee is: 1234

The house number of the employee is #64 LAJPAT NAGAR

Experience of the employee is: 12

The age of the employee is: 42
HW4


PART-A

Question 1: “this” pointer is a very useful concept in developing a program”. Justify this
statement with the help of an example implementing the usage of “this pointer”.

Answer 1: The this pointer is used as a pointer to the class object instance by the member
function. The this pointer represents an object that invokes a member function. It stores the
address of the object itself that is invoking a member function and it (this pointer )is an implicit
argument to the member function being invoked.

The this pointer is useful in returning the object(adress) of which the function is a member.

#include <iostream.h>

#include<conio.h>



   class Rectangle

   {

   public:

       Rectangle();

       void SetLength(int length) { this->itsLength = length; }

       int GetLength() const { return this->itsLength; }



       void SetWidth(int width) { itsWidth = width; }

       int GetWidth() const { return itsWidth; }



   private:

       int itsLength;
         int itsWidth;

    };



    Rectangle::Rectangle()

    {

         itsWidth = 5;

         itsLength = 10;

    }



    void main()

    {

         Rectangle theRect;

         cout << "theRect is " << theRect.GetLength() << " feet long.\n";

         cout << "theRect is " << theRect.GetWidth() << " feet wide.\n";

         theRect.SetLength(20);

         theRect.SetWidth(10);

         cout << "theRect is " << theRect.GetLength()<< " feet long.\n";

         cout << "theRect is " << theRect.GetWidth()<< " feet wide.\n";

    getch();

}
Question 2: Write a program to show the arithmetic operations on pointers?

ANSWER:

#include

using namespace std;



int main()

{ int a[] = { 22, 33, 44, 55, 66, 77, 88, 99 };

int* p = &a[3]; // p points to a[3]

cout << "p = " << p << ", *p = " << *p << endl;

++p; // p points to a[4]

cout << "p = " << p << ", *p = " << *p << endl;

p += 3; // p points to a[7]

cout << "p = " << p << ", *p = " << *p << endl;

p -= 6; // p points to a[1]

cout << "p = " << p << ", *p = " << *p << endl;

--p; // p points to a[0]

cout << "p = " << p << ", *p = " << *p << endl;

system("pause");

return 0;

}




Question 3: Write a program that dynamically allocates memory for an array of size n,
reads elements of array and sorts them in ascending order.
ANSWER 3:

            #include<iostream.h>

            #include<conio.h>

            class item

            {

                int code;

            float price;

                public:

                void getdata(int I, float j)

            {

            code=I;

            price=j;

            void display(void)

            {

            cout<<”code :”<<code<<”,”;

            cout<<”price : ”<<price<<”\n”;

            }

            };

            const int size = 10;

            int main( )

            {

            clrscr( );

            item *p =new item[n];

            item *q = p;

            int x;

            float y;
                        for(int i=0;i<n;i++)

                        {

                        cout<<”Enter code and price for item”<<(i+1)<<”\n”;

                        cin>>x>>y;

                        p->getdata( x,y);

                        p++;



                        }



                        cout<<”List of the items, we have,is \n”;

                        for(i=0;i<n;i++)

                        {

                        cout<<”\n”<<(i+1)<<”.”;

                        q->display();

                        q++;

                        }

                        return 0;

                }




PART B:

Question 4: What is the basic difference between manipulators and ios member functions
implementation? Give examples.

ANSWER 4: Manipulators are the instructions to the output stream to modify the output in
various ways. The manipulators provide a clean and easy way for formatted output in comparison
to the formatting flags of the ios class. When manipulators are used, the formatting instructions
are inserted directly into the stream. Manipulators are of two types, those that take an argument
and those that don't.

Manipulators provides the same features as that of the ios member functions and flags. But
we can use two or more manipulators as a chain in one statement .



e.g

cout<<manip1<<manip2<<manip3<<item;

// setw example
#include <iostream>
#include <iomanip>
using namespace std;

  int main ()
 {
 Int a,i;
 Cout<<Enter no.:\n “;
 Cin>>a;
 Cout<<”The output is\n\n”;
 For(i=0;i<n;i++)
 {
  Cout<<setw(4)<<”*”<<setw(3)<<a<<setw(3)<<”@”<<endl;
 }
  Return 0;
 }



Question 5: Both cin and getline() can be used for reading a string. Comment.

ANSWER 4: Yes both cin and getline functions can be used for reading a string but there is one
difference in these two.

Getline function can read the string with white spaces i.e if we input “lpu students“ it can easily
read it without giving any error in the output whereas cin function can read strings that do not
contain white spaces . This means that cin can read just one word and not a series of words such
as “lpu students” .but it can read “lpu_students” correctly.

// istream getline
#include <iostream>
using namespace std;

int main () {
 char name[256], title[256];

 cout << "Enter your name: ";
    cin>>name;

    cout << "Enter your favourite movie: ";
    cin.getline (title,256);

    cout << name << "'s favourite movie is " << title;

    return 0;
}


Output :

Enter your name: Komal // does not contain any white spaces

Enter your favourite movie: Rang De Basanti // contain white spaces



Question 6: What is the difference between opening a file with a constructor function and
opening a file with open() function? When is one method preferred over other? Illustrate
with suitable examples.

Answer : For opening a file two methods can be used

      1. Using the constructor function of the class.
      2. Using the member function open()of the class.


               The first method is useful when we use only one file in the stream.

               The second method is used when we want to manage multiple files using one stream.




Opening file using member function open() of the class is preferred over using constructor
function of the class.

The first two arguments are same as stdio‟s fopen().fname is the file name to be opened and the
mode is the string indicating how file is to be opened.



Examples- Opening a file using constructor

…..

…..
Outfile.close();

Ifstream infile(“salary”);

…..

….

Infile.close();



Opening multiple files using open()


Ofstream outfile;            //C reate stream(for output)

Outfile.open(“DATA1”); // connect stream to DATA1

……

……

Outfile.close();         //disconnect steam from DATA1

Outfile.open(“DATA2”);//Connect stream to DATA2

……

……

Outfile.close();         //Disconnect stream from DATA2

…….

……




Note that the first file is to be closed before opening the second file.this is important as the stream
        can be connected to one file at a time.

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:221
posted:1/28/2011
language:English
pages:48