Escolar Documentos
Profissional Documentos
Cultura Documentos
OOP has data as a critical component in the program development. It does not let
the data flow freely around the systems. It ties data more firmly to the functions that
operate on it and prevents it from accidental change due to external functions. OOP
permits us to analyze a problem into a number of items known as objects and then
assembles data and functions around these items. The basic objective of OOP is to treat
data 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 on
functions 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
Inheritance is the method by which objects of one class get the properties of
objects of another class. In object oriented programming, inheritance provides the
thought of reusability. The programmer can be add new properties to the existing
class without changing it. This can be achieved by deriving a new class from the
existing one. The new class will possess features of both the classes. The actual
Power of inheritance is that it permits the programmer to reuse a class that is close to
what he wants.
(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 issues
are analyzed in terms of object and the type of transmission between them. Every
object 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;
(iii) Arrays
Eg; int b[4];
int b[4] = { 2,4,3,7};
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}
(b). State the significance of function prototype and give the syntax to declare a
function
A prototype statement helps the compiler to check the return and
argument types of the function. A function prototype declaration consists of the
function 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 its
prototype declaration. If the programmer makes a mistake, the compiler flags an
error message. The function prototype declaration statement is always terminated
with semicolon.
Syntax: return_type function_name ( arg1, arg 2);
Eg: void main()
{
float sum (float, int); //function prototype
float 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 <iostream .h>
void main( )
{
int i ,x, mul=0;
cout<<”Enter the number”;
cin>>x;
for (i=1; i<10; i++)
{ mul=a*x;
cout<<”product=”<<mul;
}
3. (a). Mention the syntax of all the loops available in C++ and explain with program
examples.
For loop
Syntax: for (initialization; condition; increment/decrement)
{ statement block;
}
The for loop allows execution of a set of instructions until a condition is met. The
initialization is an assignment statement that is used to set the loop control variable.
The condition is a relational expression that determines the number of the iterations
desired or the condition to exit the loop. The increment or the re-evaluation parameter
decides how to change the state of the of the variables. These three sections must be
separated by semicolons; The body of the loop may consist of a block of statements
or single statement.
Eg:
#include<iostream.h>
void main( )
{
int j;
for (j=1;j<11;j++)
cout <<j;
}
(i) The While loop
Syntax: while(test condition)
{ body of the loop }
The test condtion may be any expression. The loop statements will be executed
till the condition is true i.e., the test condtion is evaluated and if the condtion is true,
then the body of the loop is executed. When the condtion becomes false the
execution will be out of the loop.
Eg:
#include <iostream.h>
void main( )
{
int a=1, sum=0;
while (a<=10)
{cout<<a;
sum=sum+a;
a++;
}
cout<<”sum of 10 numbers:”<<sum;
}
The do while loop
Syntax: do
{ statements:
}
while (condition);
The difference between the while and do-while loop is the place where the condition
is to be tested. In the while loop, the condition is tested following the while statement
and then the body gets executed. Where as in do-while, the condition is checked at
the end of the loop. The do while loop executes until the condition becomes false.
Eg:
# include <iostream.H>
void main( )
{ int y,x=1;
cout << “Numbers and their cubes”;
do
{ y = pow (x,3);
cout <<x<<y ;
x++;
} while(x<=10);
}
(b). What is parameter passing ? Explain the different parameter passing schemes
supported by C ++.
The main objective of passing argument to function is message passing.
The message passing is also known as communication between two functions i.e.,
between caller and callee functions. There are three methods by which we can pass
values to the function. These methods are,
(a) Pass by value
(b) Pass by address
(c) Pass by reference
Pass by value
Eg: # include <iostream.h>
Void main( )
{ int x,y;
void change (int,int);
cout<<”Enter values of x & y:”;
cin>>x>>y;
change(x,y);
cout<< “In function main”;
cout<< “values x=”<<x<<”and y=”<<y;
}
void change (int a, int b)
{
intk; k=a; a=b; b=k;
cout<< “in function change”;
cout<<” values x=”<<a<<” and y=”<<b;
}
output
Enter values of X & Y: 5 4
In function change ( )
Values x=4 and y = 5
In function main( )
Values x =5 and y =4
In this type, value of actual argument is passed to the formal argument and
operation is done of the formal arguments. Any change in the format argument does
not effect the actual argument because formal arguments are photocopy of actual
arguments. Hence, when function is called by call by value method, it does not affect
the actual contents of actual arguments.
(2) Pass by address
#include <iostream.h>
void main( )
{ int x,y;
void change (int *, int*);
cout<< “Enter values of x & y”;
cin >> x>>y:
change(&x, &y);
cout << “In main() “;
cout<< “values of x=” <<x<< “and y”<<y;
}
void change ( int *a, int *b)
{
int *k;
*k=*a;
*a=*b;
*b=*k;
cout<< “in change ( )”;
cout<<”values x=”<<*a<<”and y=”<<*b;
}
Output
Enter values x &y : 5 4
In change ( )
Values x = 4 and y=5
In main ( )
Values x =4 and y=5
In this type, instead of passing values, addresses are passed. Function operates on
addresses rather than values. Here the formal arguments are pointers to the actual
arguments. Hence changes made in the arguments are permanent.
(4) Passing by Reference:
# include <iostream.h>
void main ( )
{
void funB (int &);
int s=4;
funB (s); //s passed by reference
cout <<”Value of s=”<<s;
}
void funB(int &k)
{ k++ ; }
Output
Value of s=5;
4. (a) Explain enumerated data types: Demonstrate the usage of enumeration
constants
The enum is a keyword. It is used for declaring enumeration data types. The
programmer can declare new data type and define the variables of these data types
that can hold.
The syntax for enumerated data type
enum variable_name{ variable1,variable2, ……)
Eg:
# include <iostream.h>
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<<”day1=”<<day1;
cout<<”day2=”<<day2;
cout<<”day3=”<<day3;
cout<<”day4=”<<day4;
cout<<”day5=”<<day5;
cout<<”day6=”<<day6;
cout<<”day7=”<<day7;
}
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 the
temperature in centigrade and returns the temperature in Fahrenheit using the relation
TF = (1.8 x TC +32). Use a default value of 25 degree Celsius for TC. Write a main()
function that gets the value of centigrade from the user to test the program.
Solution: Default parameters are the values of specified parameters to be used in case
they are not passed.
“include<iostream.h>
double convTemp(float c=25.0);
int main() {
float centigrade;
double answer;
char yorn;
cout<<”\nEnter centigrade:”; cin>>centigrade;
cout<<”\n Want to enter power(y/n)?”; cin>>youn;
if(yorn==’y’)
{cout<<”\nEnter centigrade:”;
cin>>centigrade;
answer=convtemp(float centigrade);
}
else
{ answer=convtemp(float 25.0);}
cot<<”answer is”<<answer<<endl;
return 0;
}
double convtemp(float cent)
{double result;
result=(1.8*cent)+32;
return result;
}
7. Explain the array data types. What are initialized and uninitialized arrays? How are
the array elements referred in the program?
8. Write a program to use switch case to check whether the entered character belongs
to the following set. If present it should display “Yes Present”,else ”Not present”. Set
S + {a,e,1,2,%,Z,P,Q}
9. Describe new and delete operators with examples.
-------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------
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 <name of 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.
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<iostream.h>
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<<”codeno=”<<codeno;
cout<<”price=”<<price;
cout<<”quantity=”<<qtyl
}
int main( )
{
item one; //object declaration
one.show ( ); // call to member function
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 <iostream.h>
class interest
{
private:
float p_amount, rate, period;
float interest, t_amount;
public:
void in( )
{
cout<<”principle amount:”; cin >> p_amount;
cout<<” Rate of interest:”; cin>>rate;
cout<<”number of years:”; cin>>period;
interest=(p_amount*period*rate)/100;
t_amount=interest + p_amount;
}
void show( )
{
cout<<”principle amount:”<<p_amount;
cout<<” Rate of interest:”<<rate;
cout<<”number of years:”<<period;
cout<<”interest”<<interest;
cout<<”Total amount”<<t_amount;
}
};
int main( )
{
interest r;
r.in( );
r.show( );
return 0;
}
output
Principle amount: 5000
Rate of interest : 2
Number of years: 3
Interest : 300
Total amount : 530
#include <iostream.h>
int sqr (int); // function overloading
float 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<<”square=”<<sqr (a);
cout<<”square=”<<sqr (b);
return 0;
}
The function sqr( ) is overloaded for integer and float, In the first call of the function
sqr( ), an integer 15 is passed. The compiler executed integer version of the function and
returns result 225. In the second call, a float value 2.5 is passed to function sqr( ). In this
call the compiler executed the float version of the function and returns the result 6.25.
Identification: In this step we have to identify the overloaded functions considered for
the call. And the properties of the argument list specified in the function call
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 types
2. Selection: This process selects the functions from the list of candidate functions which
are 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 process
are now selected for invoking with the specified argument list. The functions so selected
are 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 default
argument.
(iii) Best match selection: This process is to select the function that matches the function
call the best. The function that matches best with the function call is called best viable
function or best match function.
(b). Write a program to swaps the contents of three variables of type int, char,
float, using overloaded functions.
2.(a). What is a function template? Can you overload function templates? If so,
explain how the overload resolution for function templates is done.
To overcome the disadvantages like time consuming, more disk space, debugging caused
by using the overloaded functions, these function template is used. A function template is
a method of writing a single generic function for a family of identical functions designed
to handle different data types.
The function template can be overloaded.
Eg:
// template function with explicit function int main ( )
#include <iostream.h> {
#include < string.h> display (100);
template<class T> display (12.34);
void display ( T x) display(‘c’);
{ cout<<”Template display”<<x: } return 0;
void display ( int x) //overloads the generic }
display( ) output:
{ cout<<”explicit display:”<<x;} Explicit display:100
Template display:12.34
Template display: c
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.
(c). what are friend functions? Mention the merits and demerits of using it.
3.(a) With the help of a general representation of CLASS, explain the terms class,
private, public, data members and member functions. Give example
(b). Define a class complex with data members real part, imaginary part and member
functions to read, print complex number and to add 2 complex numbers. Use this
class in a main function to read, print and add two complex numbers.
The scope resolution operator is the operator , which is used for defining the
member function outside the class.
And it is also used for differentiating between the local and global objects when both
having the same variable names.
#include <iostream.h> cout <<"In local scope x = "<<x<<" and
in global scope x ="<<::x<<endl;
int x = 100; ::x = 400;
cout <<"After initialization, "
void main() <<" local x = "<< x<<" global x
{ ="<<::x<<endl;
int x = 200; }
4 (a) What are constructors and destructors explain with an example? Mention its
salient features..
Constructors
If a class b has one or more constructors, one of them is invoked each time when we
define an object b of class B. The constructor creates object b and initializes it.
Constructors are also called when local or temporary objects of class are created.
Eg. B ( ) { }
Destructors
Destructors are opposite to the constructor. The process of destroying the class
objects created by constructors is done in destructor. The destructors have the same
name as their class, preceded by a tilde. A destructor is automatically executed when
object goes out of scope. The class can have only one destructor. B( )
(b).What are static data members? Explain with the help of a suitable c++ program.
Once a data member variable is declared as static, only one copy of that member is
created for the whole class. The static is a keyword used to preserve value of a variable.
When a variable is declared as static it is initialized to zero. A static function or data
element is only recognized inside the scope of the present class.
Syntax:
Static <variable definition>;
If a local variable is declared with static keyword, it preserves the last value of the
variable. A static data item is helpful when all the objects of the class share a common
data. The static data variable is accessible within the class, but its value remains in the
memory throughout the whole program.
#include<iostream.h> int main( )
class number { number a,b,c;
{ a.count( );
static int c; b.count ( );
public: c.count( );
void count ( ) return 0’
{ ++c; }
cout<<”c=”,,c; } output
}; c=1
int number ::c=0; //initialization of static c=2
member variable c=3
Here the class nuber has one static data variable c. The count () is a member functions
increment value of static member variable c by one when called. The three objects in the
main function calls the function count(), at each call to the function count(v) the variable
c 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, the
non-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 functions
using objects. When one of the objects changes the value of dat member variables, the
effect is visible to all the objects of the class.
A class within another class is called a nested class. The concept of nested class is
similar to the concept of nested structures.
#include <iostream.h> void person :: printPerson(void)
#include <string.h> {
class person cout <<"Roll number =
{ private: int rollno; "<<rollno<<endl;
char name[20]; cout <<"Name = "<<name
float percentage; <<endl;
public: class date { cout <<"Percentage =
private: int day; "<<percentage<<endl;
int month; }
int year; void main()
public: void setdate(int dd, int mm, int yyyy) { person boy;
{day = dd; month = mm; year = yyyy;
}
void printDate(void){ cout<<"Date of birth = "
<< day <<"-"<<month<<"-"<<year<<endl; //object creation
} }; //End of date class person::date dateOfBirth;
void getPerson(int rn, char nm[], float pct);
boy.getPerson(1234, "Suraj",
void printPerson(void); 89.59);
}; //End of class person cout<<"Person information is as
follows "<<endl;
void person :: getPerson (int rn, char nm[], float pct) boy.printPerson();
{
rollno = rn; dateOfBirth.setdate(10,5,1970);
strcpy(name, nm); dateOfBirth.printDate();
percentage = pct;} }
output
Person information is as follows
Roll number = 1234
Name = Suraj
Percentage = 89.589996
Date of birth = 10-5-1970
Solution: #include<iostream.h>
#include<math.h>
class power
{ int num,power,ans;
public: power (int n=9,int p=3); //declaration of constructor with default
arguments
void show()
{
cout<<num<<”raise to”<<power<<”is”<<ans:}
};
power::power (int n, int p)
{
num=n;
power=p;
ans = pow(n,p);
}
int main()
{
power p1,p2(2);
p1.show();
p2.show();
return 0;
}
output:
9 raise to 3 is 729
5 raise to 3 is 125
14. What are overloaded functions? Why are functions overloaded? Write a
program using function overloading to calculate the area of a rectangle, and
the area of a circle.
15. What are automatic and external variables? When are they created in a
program? Give the lifetime, visibility and storage class (memory used) for
these variables. solution: Lifetime is the time duration between creation and
destruction of a variable. Visibility describes the locations within a program
from which variables can be accessed. Automatic variables also called
local variables are variables defined inside a function and external variables
are those defined in main() function. Automatic variables are visible
from the function; life time is that of function; and is created in stack memory.
External variables are visible from the file; life time is that of the program;
and is created in heap memory.
16. Create a class called Distance that models distances measured in inches and
feet. Note that inches can be any real value in the range 0-11.9, and feet is an
integer. For example, the length of a room is 18’-9.5”. A constructor should
initialize them to fixed values. A member function called adddistance(),
should add two distances properly. Finally, another member function called
displays the two values of a distance in the format 18’-9.5”.
17. What are the different types of constructors? In what way these are different
from other member functions.
18. Write a simple C++ program to illustrate passing and returning of objects to
functions.
Solution
----------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------
III IA portions
(b). Write a C++ program to define a Class called Complex containing to members
real part and imaginary part and illustrate how the binary operators +, - can be
overloaded for the objects of type Complex. (10 marks).
2.(a). What is friend function? Explain how a friend function can be used to overload
++ operator with an example. (7
marks).
Operator functions can be either member functions or non-member function. When non-
member functions, we declare them as friends to a class, thereby allowing them to access
the private members of a class object.
A friend declaration is made only within a class definition. And, it begins with the key
friend. We can declare these friends in any of the three sections private, public or
protected of a class definition. If a non-member operator function needs to access the
private or protected members of a class then you have to use the friend declaration.
The friend function can be used in this situation, for eg: R=5 +P;
Where R and P are class objects
To invoke the operator member function in this statement the left hand side opeand of
overloaded operator must be a class object. To overcome this problem, a friend function
is used.
#include <iostream.h> cout<<”Before incrimination:”;
class number N.show( );
{ float x; cout<< “After incrimination:”
public: number ( float k) {x=k;} N++;
friend void operator ++ (number n) N.show( );
// friend function defined }
{ n++; } Output
void show ( ) { cout<< Before incrimination
“x=”<<x;} X=2.3
}; After incrimination
void main( ) X=3.3
{
Number N(2.3);
(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 as
copy constructor. It is used as copy constructor.
When we pass an object by value into a function , a temporary copy of that object is
created. All copy constructors require one argument, with reference to an object of that
class. Using copy constructors, it is possible for the programmers to declare and initialize
one object using reference of another object. Thus whenever a constructor is called a
copy of an object is created.
Eg;
#include<iostream.h> void main( )
class num {
{ int n; num j(50);
public: num k(j);
num ( ) { } cout <<”objct j value of n:”;
num (int k) {n=k;} j.show( );
num (num &j) //copy constructor cout <<”objct k value of n:”;
{ n=j.n; } k.show( );
void show (void ) {cout <<n; } return 0;
}; }
Output
Object j value of n:50
Object K value of n:50
(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, the
non-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 functions
using objects. When one of the objects changes the value of dat member variables, the
effect is visible to all the objects of the class.
3.(a) .What are the advantages of inheritance ? Explain the concept of multiple
inheritances
Advantages of inheritance are reusability , time saving and cost
Multiple inheritance:
#include <iostream.h>
class A{protected: int a;}; //class A declaration
class B{protected: int b;}; //class B declaration
class C{protected: int c;}; //class C declaration
class D{protected: int d;}; //class D declaration
class E:public A,B,C,D //multiple derivation
{ int e;
public: void getdata ()
{ cout<<”Enter values of a,b,c,d,e”;
cin>>a>>b>>c>>d>>e;
}
void showdata ( )
{
cout<<a<<b<<c<<d<<e;
};
void main( )
{
E x;
x.getdata( );
x.showdata ( );
}
(b). A class D has been privately derived from class B. Which of the following can be
accessed by an object of class D located in main ( )?
(i) public members of D : accessible
(ii) private members of D : not accessible
(iii) protected members of D : accessible
(iv) public members of B : not accessible
(v) private members of B : not accessible
(vi) protected members of B. : not accessible
( 6 marks).
(c). Write a suitable program to illustrate the multilevel inheritance. The program is
to create a base class called grand father and to derive it to father class which in turn
is derived to son class. Select different member functions in class declaration (8 marks).
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, in
hh;mm;ss format.
(b). What are virtual classes ? Explain with an example.
5. Discuss on the use of pointers to derived classes and pointers to class members.
6. What is the use of overloading the built in operators? Write a program to add,to
subtract, to display the two complex numbers by overloading the operators +,-and *.
7.What are the different forms of inheritance supported by C++? Explain them with
suitable examples.