Você está na página 1de 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 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

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
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 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.

(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 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;

(II) Derived data type:


(i) Pointers Eg. int *x; float *f; char *y;
(ii) Functions
Eg : main()
{
funcA();
……….
funcB();
……….
}
funcA ( )
{
statements;
}
funcB( )
{
statements;
}

(iii) Arrays
Eg; 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}
(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;
}

(b). What is an inline function? Why is it necessary to make a function an inline


function? When is it not efficient to make a function an inline function?
The C++ provides a mechanism called inline function. When a function is declared as
inline, the compiler copies the code of the function in the calling function, i.e.,
function body is inserted in place of function call during compilation. Passing of
control between caller and callee function is avoided. If the function is very large, in
such a case inline function is not used because the compiler copies the contents in the
called function that reduces the program execution speed. The inline function is
mostly useful when calling function is small. It is advisible to use the inline function
for only small functions.
Inline mechanism increases execution performance in terms of speed. The
overhead of repetitive function calls and returning values are removed. The program
using inline function needs more memory space since the inline functions are copied
at 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 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

1. (a) What is an overloaded function or function polymorphism? Explain the steps


involved 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 function
overloading of function polymorphism. Polymorphism means one function having many
forms. The overloaded function must be different in its argument list and with different
data types. The examples of overloaded functions are given below. All the functions
defined should be equivalent to their prototypes.
Eg:

#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.

The three Steps involved in resolving a set of overloaded functions

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.

#include <iostream.h> //function to swap two integers


#include <string.h> void swap (int *a, int *b)
{
void swap (int *a, int *b); int temp = *a;
void swap (float *a, float *b); *a = *b;
void swap (char str1[], char str2[]); *b = temp;
}
void main() //function to swap two float variables
{ void swap (float int *a, float *b)
int x, y; {
char s[10], t[10]; float int temp = *a;
*a = *b;
cout <<"Enter the value of x and *b = temp;
y"<<endl; }
cin >> x>>y;
cout<<"Enter two strings"<<endl; //function to swap two strings
cin >> s>> t; void swap(char str1[], char str2[])
{
swap (&x,&y); char temp[10];
cout <<"x="<<x <<" and y="<<y<<endl;
strcpy(temp, str1);
swap (s,t); strcpy(str1,str2);
cout<<"string1="<<s<< " and strcpy(str2,temp);
string2="<<t<<endl; }
}

Enter the value of x and y


75
89
Enter two strings
learn
earn
x=89 and y=75
string1=earn and string2=learn

2.(a). What is a function template? Can you overload function templates? If so,
explain how the overload resolution for function templates is done.

A function template is a single generic function which is used to generate specific


instances of a function with arbitrary data types. All or a subset of a function’s
parameters and return types are parameterized. The general form of declaring a function
template in c++ is as follows,
Template < class T> T function_name (T parameters)
{
Body of function with type T
}
where template, class -> are keywords
T-> is the parameterized data type
Function name -> is the name of the function.

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.

#include<iostream.h> p1=power (10,4);


#include<math.h> cout<<”power=”<<p1;
template<class T> p2=power ( 2.5,4.0);
void power ( T a,T b) cout<<”power=”<<p2;
p3=power (2345.56,7896.45);
{ return ( pow (a,b));} cout<<”power=”<<p3;
int main ( ) return 0;
{ }

(c). what are friend functions? Mention the merits and demerits of using it.

The private members of a class cannot be accessed by the non-member


functions. But there may be some situations wheterit is needed to access the private
mebers of a class by the non member functions. This can be achieved by changing the
access speicifer of private members to public. The attempt to change the access specifier
of the private members to public, violates the underlying concept of data hiding and
encapsulation. So, we can overcome this problem by declaring the non-member functions
as friend functions.
The friend keyword is used to declare friend functions.
A friend function is not in the scope of the class to which it has been declared as friend.
A friend function can be declared iehter in the private or public section of a class.
Usally friend function has the object as its arguments.
A friend function cannot access the class members directly. An object name followed by
dot operator, followed by the individual data member is specified for valid access.
Eg.
#include<iostream.h> int average(ff num)
class ff {return ((num.x+num.y)/2.0);}
{ int x,y; void main( )
public: void accept(void) {
{ cout<<”enter the values”; ff cob;
cin>>x>>y; } cob.accept();
friend int average(ff num); cout<<”average=”<<average(cob);
}; }

3.(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> cout<<”codeno=”<<codeno;
class item cout<<”price=”<<price;
{ private: int codeno; // private section cout<<”quantity=”<<qty;}
starts int main( )
float price; { item one; //object declaration
int qty; one.show ( ); // call to member function
public: //public section starts return 0;
void show( ) }
{ codeno=125; price=195;qty=200;

(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.

#include<iostream.h> void sum( complex a,complex b)


class complex { complex c;
{ private: // private section starts c.x = a.x + b.x;
float x,y; // real & imaginary part c.y = a.y +b.y;
float ans; cout<<c.x<<”+j”<<c.y;
public: //public section starts }
void getdata( ) int main( )
{ cout<< “Enter the value of x”;cin>>x; {
cout<<”enter the value of y”; cin>>y;} complex c1, c2,c3; //object
void show( ) declaration
{ cout<<” the value of x=”<<x; c1.getdata( ); // call to member function
cout<<” the value of y=”<<yx; c1.show ( ); // call to member function
} 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 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( )

#include <iostream.h> ~sample() //Destructor


class sample { cout <<"In desructor. Object
{ private: int x; dies"<<endl;
public: sample(void) //constructor }
{ x = 0; };//End of class sample
cout <<"In constructor, "<<"x = "<< x void main()
<endl; {
} sample s1;
void printx (void) s1.printx();
{ }
cout <<"In printx, x = "<< x <<endl; } Output
In constructor, x = 0
In printx, x = 0
In desructor. Object dies

Characteristics of constructors and destructors


Constructors
1. Has the same name as that of the class it belongs.
2. Is executed when an object is declare.
3. Constructors have neither return value nor void
4. The main function of constructor is to initialize objects & allocate appropriate memory
& objects.
5. Though constructors are executed implicitly, they can be invoked explicitly.
6. The constructor without arguments is called ad default constructors.
Destructors
1. Like constructor, the destructor does not have return type and not even void.
2. Constructor and destructor cannot be inherited, though a derived class can call
the constructors and destructors of the base class.
3. The destructor does not have any argument.
4. The destructors neither have default values nor can be overloaded/
5. Programmer cannot access addresses of constructors and destructors.

(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.

#include <iostream.h> void main()


class checkObject {
{ private: static int num; checkObject cob1;
public: static int totalObjects(void) checkObject :: totalObjects();
{ num = num + 1; cob1.display();
return num; checkObject cob2;
} checkObject :: totalObjects();
void display (void) cob2.display();
{ }
cout <<"Object "<<num<<" is created so /*----------------------------
count = "<<num <<endl; Output
} Object 1 is created so count = 1
}; //End of class definition Object 2 is created so count = 2

int checkObject :: num = 0; -----------------------------*/

(c). Explain the concept of nested classes with an example.

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

(c). 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

6. Distinguish between normal function and inline function


7. Write a C++ program using function overloading to compute square of a
number and cube of a number.
8. Write an interactive program using ‘switch case’ statement to find the roots of
a quadratic equation (ax2 + bx + c) = 0, for handling all the possible cases.
9. Write a small program with an inline function to find the largest among the
three numbers, by using conditional operators.
10. What is function polymorphism ? Write a C++ program to illustrate function
polymorphism to compute square of a number belonging to different data
types and with different arguments.
11.
12. Explain the friend function. Illustrate with a program to demonstrate how
friend function can work as bridge between different classes with respect to
your program . Explain what is forward declaration.
Solution: The private members of a class cannot be accessed by the non-member
functions. But there may be some situations where it is needed to access the private
members of a class by the non member functions. This can be achieved by changing the
access specifier of private members to public. The attempt to change the access specifier
of the private members to public, violates the underlying concept of data hiding and
encapsulation. So, we can overcome this problem by declaring the non-member functions
as friend functions.
The friend keyword is used to declare friend functions.
A friend function is not in the scope of the class to which it has been declared as friend.
A friend function can be declared either in the private or public section of a class.
Usually friend function has the object as its arguments.
A friend function cannot access the class members directly. An object name
followed by dot operator, followed by the individual data member is specified for valid
access.
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 in
the program.
#include<iostream.h>
Class ABC; // forward declaration
Class 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 <<m.x;
else
cout<<n.a;
}
int main( )
{
ABC abc;
abc.setvalue(10);
XYZ xyz;
xyz..setvalue(20);
max (xyz,abc); // friend function called
return 0;
}
output: 20

13. Explain Dynamic initialization of objects.

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

#include < iostream.h> int main()


Class Complex // x+iy form {
{ float x,y; complex a,b,c; // objects created
public: void input(float real, float imag) a.input(3.1,5.65);
{x = real; y=imag;} b.input(2.75,1.2);
friend complex sum(complex,complex); c=sum(a,b);
void show (complex); cout<<’a=”;
}; a.show(a);
complex sum(complex c1,complex c2) cout<<”b=”;
//function with passing and returning object b.show(b);
{ complex c3; //object cout<<”c=”;
c3.x =c1.x + c2.x; c.show (c);
c3.y = c1.y + c2.y; return 0;
return (c3); // returning object }
} output:
void complex::show(complex c) a=3.1+j 5.65
{ cout<<c.x<<”+j”<<c.y<<endl;} b=2.75+j 1.2
c=5.85+j 6.85

19.Explain the concept of overloading of constructors.


A class may contain multiple constructors. The concept of multiple
constructors in a class provides more flexibility.
#include <iostream.h>
class point
{
private:intx,y;
public: point (void) // default constructor
{ x = 0;y = 0; }
point (int xpos,int ypos) // constructor with two arguments
{ x = xpos; y = ypos;}
void display (void)
{ cout<<”x=”<<x<<endl;
cout<<”y=”<<y<<endl;
}
};
void main()
point p1,p2(10,20); //objects are created and constructors are called
cout<<point p1 is”<<endl;
p1.display()’
cout<<”point p2 is”<<endl;
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 multiple
definitions 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 data
types. 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 natural
manner as the variables of basic data types. Operator overloading provides the capability
of redefine the language in which working operator can be changed.
Syntax:
return type operator operator_symbol (parameters)
{
statement;
}
Eg.
#include <iostream.h> void main ( )
class number {
{ public: int x; number A(2,3),B(4,5),C;
int y; A.show( );
number ( ) { }//zero argument constructor. B.show ( );
number ( int j, int k)// Two argument C = A+B;
constructor C.show ( );
{ x=j; y=k;} }
number operator + (number D)
{ number T; output
T.x = x+D.x; x=2 y=3
T.y=y+D.y; x=4 y=5
return T; } x=6 y=8
void show ( )
{ cout<<”x=”<<x<<”y=”<<y; }
};

Steps involved in operator overloading

• Overloading of an operator cannot change the basic idea of an operator. When an


operator is overloaded, its properties like syntax, precedence, and associatibity
remain constant. For Eg. A=A+B;
• Overloading of an operator must never change its natural meaning. Only existing
operators can be overloaded. We cannot create a new operator.
• Few operators cannot be overloaded to operate in the same manner like built in
operators. Eg. . , ::, #, @,
• Creating a class that defines the new data type.
• Declaring the operator function, operator opr ( ): This must be done in public
section of a class.
• When binary operators are overloaded using friend functions, it requires two
arguments whereas when overloaded using member function, it requires one
argument.

(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).

#include <iostream.h> Cout<<”q->quit”;


class complex Cout<<”option, please?\n”;
{ }
float real,imag; void main ( )
public: {
complex ( ) //zero argument constructor complex a,b,c;
{ int ch;
real=imag=0; void menu(void);
} cout<<enter a first complex no.”;
complex operator + (complex a, complex cin>>a.real>>a.imag;
b) cout<< “enter a second complex no.”;
{ cin >>b.real>>b.imag;
complex c; while ((ch=getchar ( ) )!=’q’)
c.real= a.real+b.real; { switch (ch)
c.imag=-a.imag+b.real; {
return c; case’a’:c=a+b;
} cout <<”addition”;
complex operator - (complex a, complex cout<<c.real<<”+I”<<c.imag;
b) break;
{ case”s”:c=a-b;
complex c; cout<<”subtraction”;
c.real= a.real-b.real; cout<<c.real<<”+i”<<c.imag;
c.imag=-a.imag-b.real; break;
return c; }}
} }
};
void menu(void)
{cout<<”complex no.opeations;”;
cout<<”menu( )”;
cout<<”a->addition”;
cout<<”s->subtraction”;

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.

#include <iostream.h> void main()


class checkObject {
{ private: static int num; checkObject cob1;
public: static int totalObjects(void) checkObject :: totalObjects();
{ num = num + 1; cob1.display();
return num; checkObject cob2;
} checkObject :: totalObjects();
void display (void) cob2.display();
{ }
cout <<"Object "<<num<<" is created so /*----------------------------
count = "<<num <<endl; Output
} Object 1 is created so count = 1
}; //End of class definition Object 2 is created so count = 2

int checkObject :: num = 0; -----------------------------*/

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).

#include <iostream.h> void father :: print(void)


#include <conio.h> {
class grandFather grandFather::display(); //accessable
{ to the derived class
private: char name[25]; cout<<"Qualification =
int age; "<<qualification<<endl;
public: char color[15]; cout<<"Salary = "<<salary<<endl;
void getData(); cout<<"IQ = "<<IQ<<endl;
void display(); }
}; void son :: input(void)
{
class father : public grandfather //derived father::read(); //accessable to the
class: level 1 derived class
{ class son : public father//derived class: cout<<"Enter the Hobby : ";
level 2 cin >>hobby;
{ }
private: char hobby[20]; void son :: output(void)
public : void input(); {
void output(); father::print(); //accessable to the
}; derived class
void grandFather::getData() cout<<"Hobby = "<<hobby<<endl;
{ }
cout<<"Enter the name : "; void main()
cin >>name; {
cout<<"Enter the age : "; son s1;
cin >>age; cout<<"Enter son's
cout<<"Enter the color: "; information..."<<endl;
cin >>color; s1.input();
}
void grandFather::display() cout<<"\nSon's information is as
{ follows..."<<endl;
cout<<"Name = "<<name<<endl; s1.output();
cout<<"Age = "<<age<<endl; }
cout<<"Color = "<<color<<endl; /*----------------------------------
} Output
void father :: read(void) Enter son's information...
{ Enter the name : Sharan
grandFather::getData(); Enter the age : 28
//accessable to the derived class Enter the color: black
cout<<"Enter the qualification : "; Enter the qualification : BE
cin >>qualification; Enter the salary : 25000
cout<<"Enter the salary : "; Enter the IQ : 90
cin >>salary; Enter the Hobby : painting
cout<<"Enter the IQ : ";
cin >>IQ; Son's information is as follows...
} Name = Sharan
Age = 28
Color = black
Qualification = BE
Salary = 25000
IQ = 90
Hobby = 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, in
hh;mm;ss format.
(b). What are virtual classes ? Explain with an example.

#include <iostream.h> void DC2:: get_k()


#include <conio.h> { cout<<"Enter the value of k"<<endl;
class BC1 cin>>k;
{ }
protected: int i;
public: void get_i(); void DC2:: put_k()
void put_i(); { cout<<"k = "<<k<<endl;
}; }
void DC3:: print_sum()
class DC1 : virtual public BC1 {
//virtual base class sum = i+j+k;
{ put_i();
protected: int j; put_j();
public: void get_j(); put_k();
void put_j(); cout<<"\nSum = "<<sum<<endl;
}; }
class DC2 : virtual public BC1 //virtual void main()
base class {
{ DC3 d3;
protected: int k; clrscr();
public: void get_k(); d3.get_i();
void put_k(); d3.get_j();
}; d3.get_k();
class DC3 : public DC1, public DC2 cout<<"\n";
{ d3.print_sum();
private: int sum; }
public: void print_sum(); /*-------------------
}; Output
void BC1:: get_i() Enter the value of i
{ cout<<"Enter the value of i"<<endl; 6
cin>>i; Enter the value of j
} 7
void BC1:: put_i() Enter the value of k
{ cout<<"i = "<<i<<endl; 8
}
void DC1:: get_j() i=6
{ cout<<"Enter the value of j"<<endl; j=7
cin>>j; k=8
} Sum = 21
void DC1:: put_j() -------------------*/
{ cout<<"j = "<<j<<endl;
}

(c). What is ‘this’ pointer?

#include <iostream.h> number n1, n2; //object creation


class number n1.setValue(30);
{ private: int x; n2.setValue(80);
public: void setValue (int d)
{ this->x = d; n1.displayValue();
} n2.displayValue();
void displayValue(void)
{ } //End of main
cout <<"x = "<< this->x <<endl; /*--------------------------------
cout <<"Address of the object = Output
"<<this<<endl; x = 30
} Address of the object = 0x8fa9fff4
}; //End of class definition x = 80
void main() Address of the object = 0x8fa9fff2
{ -----------------------------------*/

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.

Você também pode gostar