OOPS Unit 1
OOPS Unit 1
OOPS Unit 1
UNIT – I
Syllabus:
destructors
PART – A
3. Define objects.
Definition1:
Definition2:
4. Define class.
Definition:
o ENCAPSULATION:
‗The wrapping of data and functions into a single unit (called class)
is known as encapsulation. Data is not accessible to the outside world.
Definition:
―The smallest individual units in a program are known as tokens .C++ has
following tokens‖:
4. String
5. Operator
Definition:
This is a list of reserved keywords in C++. Since they are used by the
language, these keywords are not available for re-definition or overloading.
Rules for naming the identifiers in C++.
Example: enum, explicit, export, extern, false, float, for, friend, goto, if
Definition:
―The global version of a variable cannot be accessed from within the inner
block in C program. C++ solves this problem by introducing new operator : :
called scope resolution operator.This is used to un cover a hidden variable
and takes the following form
:: variable -name
Example:
Class MyClass
public:
};
// Function Code
Syntax:
Example:
#include<stdio.h>
#include<conio.h>
#define NUM 15
void main()
int a=NUM;
getch();
here #define is a preprocessor. Its job is to replace all the entries named
NUM as 15. So that the compiler works with the constant 15...
……..
…......
int n =strlen(string);
……..
float area=3.14*rad*rad;
Thus declaration and initialization is done simultaneously at the place where
the variable is used for the first time.
23. What are reference variable?
A reference variable provides an alias(alternative name) for a
previously defined variable. Total, then sum and total can be used
interchancheably to represent that variable.
Syntax:
Data-type &reference-name = variable-name
Example:
float total = 100;
float sum = total;
24. What is the difference between Pointer and a reference? [Nov/Dec
2011]
Pointer :
It is used to store address of other variables
Eg: int *p;
int x;
p=&x;
*p=10;
Reference:
It provides an alias for previously defined variable
Syntax:
datatype &reference_name = variable_name;
Pass by reference
37. What is an abstract class in cpp in C++? [Nov/Dec 2012]
Definition:
―A class without any object is known as abstract class. An abstract class is
designed to act as a base class (to be inherited by other classes). It provides
a base upon which other classes may be built‖
38. What is Polymorphism? What are the types of Polymorphism?
Runtime Polymorphism
int m,n;
public:
integer( ) //default constructor
{
m=0;n=0;
}
integer(int a,int b) //parameterized constructor
{
m=a; n=b;
}
integer(&i) //copy constructor
{m=i.m;
n=i.n;
}
void main()
{
integer i1; //invokes default constructor
integer i2(45,67);//invokes parameterized constructor
integer i3(i2); //invokes copy constructor
}
49. What is the ambiguity between default constructor and default
argument constructor?
The default argument constructor can be called with either one
argument or no arguments. When called with no arguments, it becomes a
default constructor. When both these forms are used in a class, it cause
ambiguity for a statement such as A a; The ambiguity is whether to call
A::A() or A::A(int i=0)
50. Define default argument constructor
The constructor with default arguments are called default argument
constructor
Example:
Complex(float real,float imag=0);
The default value of the argument imag is 0
The statement
complex a(6.0)
assign real=6.0 and imag=0
the statement
complex a(2.3,9.0)
―The function which bears the same name as class itself, preceded by
―tilde ~‖ symbol. The destructor is automatically called with the object
goes out of scope‖.
EXAMPLE: ~ integer().
PART – B
1. Explain about procedure oriented programming in detail.
Main Program
Function 4 Function 5
Function 6
Function 7 Function 8
Global data
Global data
Object A Object B
Data Data
Functions Functions
Functions
Data
Object C
Definition: ―OOP is a technique where the real world entities are defined as
class hierarchies and we can manipulate them using a pointer to the root or
base class of the hierarchy.‖
1. OBJECTS:
Note:
Objects take up space in the memory and have associated address
like record in Pascal or structure in c.
EXPLANATION:
STUDENT
Object: STUDENT
Total
DATA
Name
Date of Birth Average
Marks
………
FUNCTIONS Display
Total
Average
2. CLASSES:
Display
………
2. CLASS:
Definition:
―The entire set of date and code of an objects made as a user-defined
date type with the help of a class ―. C++ enables to define a class that is
similar to struct of C but with addition of functions members. Thus a class
is a collection of similar type‖.
EXPLANATION:
DATA ABSTRACTION :
ENCAPSULATION:
‗The wrapping of data and functions into a single unit (called class) is
known as encapsulation. Data is not accessible to the outside world.
EXPLANATION:
Only functions wrapped in the class can access it.
Functions provide interface between objects data and program.
ABSTRACT DATA TYPE:
Definition1:
―Inheritance is the process by which objects of one class acquire the
properties of objects of another class. It supports concept of hierarchical
classifications‖.
Definition2:
―It is a mechanism of extending an existing class into a new class. The
new class will have all the attributes to the old class plus some of its own.
The new class is said to the inherited or derived from old class.
EXPLANATION:
Bird
Attributes
Feathers
Lay Eggs
5. POLYMORPHISM:
EXPLANATION:
Operation exhibit different behaviors in different instances.
Extensively used in implementing inheritance.
Supports operator over loading ,function over loading
Example: Particular word with severed different meanings depending on
context
Example: POLYMORPHISM
Shape
Draw( )
EXPLANATION:
Binding refers to the linking of a procedure call to be executed in
response to the call.
At run-time, the code matching object under current reference will be
called.
Example:
employee. Salary (name);
employee.salary(name);
C C++
It is a kind of structure oriented It is an object oriented programming
programming language language
10. What are the different data types supported by C++? [April/May
2008]
Data types in C++ can be classified under various categories as shown
in the below figure
Derived
User Defined
Type Built-in Type Type
Structure Array
Union Function
Class Pointer
Enumeration Reference
C++ supports integer (int), real (float and double) and character
(char) basic data types.
int
The int data type is used for signed integer values.
The data type can be modified with the unsigned
modifier for use with unsigned values.
float
The float data type is used for 32 bit floating point
values.
double
The double data type is used for 64 bit double precision
floating point values.
char
The char data type is a one byte value.
This data type can also be modified with the unsigned
modifier for use with unsigned byte values.
void :
It is a null or empty data type.
It is a functions does not return any values .
void data type is used as return type to return null
values
E.g: void getdata( ); // function with no return value
void putdata(void); // function that takes no arguments
void *p; // creates general purpose data type
User defined data type:
Some of the user defined data types in C++ are Structure, Union, and
Enumerated
Structure:
It is collection of variables which can be of different types
Syntax:
struct struct-type-name{
type name1: length;
type name2: length;
.
.
type nameN : length;
}variable_list;
Syntax:
union union-type-name{
type member-name;
type member-name;
}union-variables;
Enumeration:
enum is a keyword which automatically enumerates a list of
words by assigning values 0,1,2,3…
Syntax:
enum enum_name{list of names}var list;
Eg:
enum Boolean {TRUE,FALSE}
enum dyas{Sunday… Saturday}
enum color{Red=1,Blue, Green=5, Orange}
Derived data types:
Some of the derived data types are Arrays, Function and pointer
Arrays:
It is used to represent the similar data type
Eg: int a[10];
char name[20];
Function:
Self contained program structure that performs a specific task
{
int z;
z=x+y;
return z;
}
Pointer :
It is used to store address of other variables
Eg: int *p;
int x;
p=&x;
*p=10;
Constant Pointer:
Constant pointer is the one that cannot point to
anything other than what it is pointing to at the time of
its definition
Value assigned to it doesn‘t change throughout the
program
Value stored in the constant pointer is address of
another variable
Address itself cannot be changes but however the
content of that address can be changed
Eg:
int value=10;
int *const p= &value; // constant pointer
*p=100; //allowed , contents can be
changed
p++; //not allowed , pointer
address itself can‘t be changed
Pointer to constant:
It is a pointer variable that can point any memory
location, but the content of the memory location to
which it points cannot be modified.
Eg:
int value=10;
int const*p=&value;
*p=100; // invalid, content at the memory
location cannot be changed
Reference:
It provides an alias for previously defined variable
Syntax:
datatype &reference_name = variable_name;
Variables:
Variables are used to store different values
In C++, variable can be declared anywhere in the
program before its first usage
Variable must be declared and it must be initialized
before it is used.
Declaration of variables:
Eg: int a;
char c;
Initialization of variable:
The variable can be assigned in two ways either in
normal initialization or in dynamic initialization
Normal Initialization:
The normal initialization is also called as compile
time initialization.
Value of the variable is known to the compiler at
the time of compilation
Eg:
int a= 10;
Dynamic initialization:
It is also called as run time initialization
Values of the variable is assigned at the time of
execution
Eg:
int a, b;
cin>>a;
cin>>b;
int c;
c=a*b;
cout<<c;
11. What are the operators available in C++? Explain in detail about it.
All the C++ operators work in an identical manner as in C. Some of
the old operators have new meaning in C++.Some of the new operators
introduced in C++ is listed below:
Operator Meaning
:: Scope resolution operator , it is used to indicate a
member of a specified class
::* A member pointer operator
* Pointer to member using object. I t is used to
indicate a pointer to a member of a specified class
->* Pointer to member using pointer to object operator
Delete Memory release operator
New Memory allocation operator
reinterpret_cast Casting operator which is used to cast from any type
to any other type
const_cast Removing the const nature of a variable while
casting
dynamic_cast casting operator that can be used to safeguard
against irrelevant casting
Typeid Used to find type of an object at run time. Useful for
handling exceptions
Throw useful for throwing an exception at the time of an
error
Eg:
#include<iostream. h>
int m=10; // global variable m
void main ( )
{
int m=20; // local variable m
cout<<‖m=‖<<m<<‖\n‖;
cout<<‖: : m=‖<<: : m<<‖\n‖;
}
output:
20
10 (: : m access global m)
Scope resolution operator is used to define the function outside the class.
Syntax:
return type <class name> : : <function name>
Eg:
void x : : getdata( )
Initialization of the memory using new operator can be done. This can
be done as,
Delete operator is used to release the memory space for reuse. The
general form of its use is
Delete pointer-variable;
FloatVar=(float)IntVar;
FloatVar=float(IntVar);
Function Overloading:
o When a function redefined with different set of arguments, then
it is known as overloaded function. This process is known as
function overloading
o Function overloading means we can use the same function
name to create functions that perform a variety of different
tasks.
o For example define a function Add(int,int), this function can be
redefined as Add(float,float),this function is now overloaded
function
o In first case the function Add( )is used to add two integer
values, in the second case, the same function is used to add
two float values.
o The function Add( ) performs different tasks depends upon the
value passed to it.
Rules to overload a function:
o To overload any function, the function should have an
argument
o The overloaded function should differ only on arguments
o During the overloading, the basic meaning of the overloaded
function should not be allowed to change. That is the Add( )
function should not be used for performing arithmetic
operations other than addition.
o The return type of the function can be similar or different type.
Types of function overloading:
A function is overloaded in the following ways
o Function overloading based on different argument types
o Function overloading based on different number of arguments
o Function overloading based on different sequence of
arguments
o Function overloading based on different argument types
Program for Function Overloading With Different Types Of Arguments
#include<iostream.h>
#include<conio.h>
}
void Display(int x) //defined to display an integer value
{
cout<<x<<‖\t‖;
}
void Display(double d) //defined to display a double value
{
cout<<d<<‖\t‖;
}
void Display(char a) //defined to display a character value
{
cout<<a<<‖\t‖;
}
Sample output:
10 2.56 c
Explanation:
o In this program, the function Display( ) is first defined to
display an integer value .The same function is redefined to
display a double value, and a character value.
o Here the same function behaves differently when called with
integer value, double value and character value.
o The compiler automatically calls the correct version of the
function based upon the type of data used as an arguments
o The character value must be placed with single quotes during
function call.
Sample output:
x:10
x:10y:20
x:10y:20z:30
Explanation:
The function here differs based on the number of arguments
rather than the type of arguments.
The function Display( ) is defined to display one integer value.
the same function is redefined to display two and three integer
values respectively
The compiler calls the correct version of the function based
upon the number of data used as arguments
The number of argument may be same or different type.
Function overloading based on different sequence of arguments:
The function to be overloaded uses different sequence of arguments,
the following program illustrates this,
#include<iostream.h>
#include<conio.h>
using namespace std;
void Display(int,double); //first argument is int, second is double
void Display(double,int); //first argument is double .second is int
void main( )
{
Display(10,12.5); //sequence is int and double
Display(12.5,10); //sequence is double and int
}
Explanation:
The function Display ( ) is declared and defined to the different
sequence of arguments.
In the first call, the order of value passed to the function is integer
and double value whereas in the second call the order of passing
value is double and integer.
The compiler calls the correct version of the function based upon the
sequence of data used as an argument
Similarity:
The function calls in both cases do not differ.
#include<iostream.h>
#include<conio.h>
using namespace std;
class sample
{
private:
int a,b;
public:
sample(int x , int y)
{
a=x;
b=y;
}
friend int max(sample); //friend function declaration ,object
is used as an argument
};
int Max(sample s) //friend function defined like a
regular function
{
if(s.a>s.b) //the access of private data
members
return s.a;
else
return s.b;
}
void main( )
{
sample s1(100,50);
int m = Max(s1); //friend function called like a
regular function
cout<<‖Max:‖<<m;
}
Sample output:
Max:100
Program for friend function can be friend with more than one class.
#include<iostream.h>
#include<conio.h>
using namespace std;
class two; //forward declaration
class one
{
private:
int x;
public:
one(int a) //constructor function
{
x=a;
}
friend int Max(one,two); //friend function declaration
};
class two
{
private:
int y;
public:
two(int b) //constructor function
{
y=b;
}
Sample Output:
Max:100
Explanation:
Friend Class:
o In addition to declaring individual friend functions, it is
possible to have an entire class to be friend to other classes
o This can be useful if a class is used with another class that all
the methods in that class need access to the private members
of the other class
o The trust is one directional that is ,if class1 defined class 2 to
be its friend, the class2 member functions can access private
variables of class1 but the class1 member function cannot
access private variables of the class2
#include<iostream.h>
#include<conio.h>
using namespace std;
class two; //forward declaration
class one
{
private:
int x;
public:
one(int a) //constructor function
{
x=a;
}
};
class two
{
private:
int y;
public:
two(int b) //constructor function
{
y=b;
}
Sample Output:
Max:100
15. Explain the concept of pointers with an example program written in
c++. [April/May 2010]
Pointers offer a unique approach to handle data in C and C++.
Pointer is a derived data type that refers to another data variable by
storing the variable‘s memory address rather than data.
A pointer variable defines where to get the value of a specific data
variable instead of defining actual data.
&-address of operator.
*-used to retrieve the address of a variable.
Void Pointer
It is also known as generic poimter, which refer to variables of any
data type.
Before using void pointers, we must type cast the variables to the
specific data types that they point to.
Manipulation of Pointers
Indirection operator (*) or deference operator is used to access the
pointer variable content.
Syntax
* pointer_variable;
PROGRAM
//Manipulation of pointers
# include <iostream.h>
#include<conio.h>
void main
{
int a=10,*Ptr;
Ptr=&a;
cout<<‖The value of a is:‖<<a<<endl;
*Ptr=(*Ptr)/2;
cout<<‖The value of a is :‖<<(*Ptr) ;<<endl;
}
OUTPUT
The value of a is: 10
The value of a is: 5
{
int num [ ]={10,20,30,40,50};
int *Ptr;
int i;
cout<<‖The array values are:\n‖;
for(i=0;i<5;i++)
cout<<num[i]<<‖\n‖;
\\ initializing the base address of Str to Ptr */
Ptr=num;
/*Printing the value in the array*/
cout<<‖\n value of Ptr:‖<<*Ptr;
cout<<‖\n‖;
Ptr++;
cout<<‖\n value of Ptr++:‖<<*Ptr;
cout<<‖\n‖;
Ptr--;
cout<<‖\n value of Ptr--:‖<<*Ptr;
cout<<‖\n‖;
Ptr=Ptr-1;
cout<<‖\n value of Ptr-1:‖<<*Ptr;
cout<<‖\n‖;
Ptr + = 3;
cout<<‖\n value of Ptr + = 3:‖<<*Ptr;
Ptr - = 2;
cout<<‖\n‖;
cout<<‖\n value of Ptr - = 2:‖<<*Ptr;
cout<<‖\n‖;
getch( );
}
OUTPUT
The array values are
10
20
30
40
50
Value of Ptr : 10
Value of Ptr ++ : 20
Value of Ptr-- : 10
Value of Ptr+2 : 30
Value of Ptr-1 : 20
Value of Ptr+3 : 50
Value of Ptr-=2 : 30
16. What are the advantages of using default arguments? Explain with
an example program.
DEFAULT ARGUMENTS:
Definition:
―C++ allows us to assign default values to the function parameters,
when the function is declared. In such case we can call a function without
specifying all its arguments .Used in situation where some arguments have
some value‖.
Example: bank interest.
float amount(float principal,int period, float rate=0.15);
Note:
―The compiler looks at the prototype to see how many arguments a function
uses and alerts the program for possible default values‖.
ADVANTAGES:
Default argument add new parameter to existing function
Used to combine similar function into one
PROGRAM:
#include<iostream.h> // header part
#include<conio.h>
int main()
{
clrscr();
volume=vol(length);
cout<<"\n Volume with one argument passed = "<<volume<<endl;
volume=vol(length,width);
cout<<"\n Volume with two argument passed = "<<volume<<endl;
volume=vol(length,width,height);
cout<<"\n Volume with all argument passed = "<<volume<<endl;
getch();
return 0;
}
17. Write a program to demonstrate how a static data is accessed by a
static member function.
STATIC MEMBER FUNCTIONS:
Definition:
―A function which precedes the static keyword before the definition. It
can only access the static members of the class. Though static member
functions are defined like member functions, they are not truly members.
SYNTAX:
class_name :: function_name;
static void disptotal();
PROPERTIES OF STATIC MEMBER FUNCTION:
A static function can have access to only other static members
declared in the same class.
A static member function can be called using the class name
PROGRAM:
//Static member variables and functions
class test
{
int code;
static int count; // static variable
public:
void setcode(void)
{
code=++count;
}
void showcode(void)
{
cout<<‖Object Number:‖<<code<<‖\n‖;
}
static void showcount(void) // static member function
{
cout<<‖count:‖<<count<<‖\n‖;
}
};
int test::count;
int main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount(); // Accessing static member function
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
return 0;
}
Note: static member variable and static member function can be accessed
within class but cannot using object.
INLINE FUNCTIONS:
Definition:
Example:
inline double cube (double a)
{
return (a*a*a);
}
#include<iostream>
using namespace std;
inline float mul( float x , float y)
{
return (x*y)
}
inline double div (double p , double q)
{
return (p/q)
}
int main()
{
float a= 12.34;
float b= 9.8;
cout<< mul (a,b)<<‖\n‖;
cout<< div (a,b)<<‖\n‖;
return 0;
}
EXPLANATION:
Abstract classes are usually outcome of generalization process which
finds out common elements of the classes and stores them in a base class.
20. Define polymorphism. Describe the type of polymorphism with
example. [May/Jun 2013]
Polymorphism
―Polymorphism is the property of the same object to behave differently in
different contexts given the same message‖
Two types of polymorphism
1. Compile time polymorphism
2. Run time polymorphism
Polymorphism
Runtime
Compile Time
Overview
Introduction (Compile Time polymorphism and Runtime
Polymorphism)
Pointer object
This pointer
Compatibility of derived and base class pointers
Virtual Functions
Static vs Dynamic Binding
1. Introduction
Compile Time Polymorphism
Achieved by function overloading and operator overloading
Function overloading:
A single function name can be used for various purposes (with
different arguments)
Operator overloading:
Single operator is used to achieve multiple operations (with different
type of operands)
Runtime polymorphism
Run time polymorphism is achieved by virtual functions.
Resolving function call at run time is known as runtime or late or
dynamic binding.
Runtime polymorphism allows selecting the suitable function at run
time.
2. Pointer object
Pointer object is a variable containing an address of an object which is
similar to pointer variable.
Use & operator to get the address of an object.
Advantages
Pointer object is used to achieve a run time polymorphism.
It is a polymorphic object to access member functions of different
classes.
3. This Pointer
Definition
The name ―this‖ is a keyword. The pointer this allows to access the current
object only.‘ This‘ pointer is used within a method to access an object
member. It is also used to return the address of the current object.
Program
#include<iostream>
#include<conio>
using namespace std;
class A
{
private:
int x;
public:
A( ) {}
A(int a)
{
this->x=a; //accessing data member
}
A disp( )
{
return *this; //returns the address of an object
}
};
void main( )
{
A(10);
A a1,a2;
a2=a1.Disp( );
}
4. Compatibility of derived and base class pointers
#include <iostream>
using namespace std;
class Base
{
public:
virtual void runme() { cerr << "Base" << endl; }
};
};
int main()
{
Base *p = new Derived; // get rid of parens
p->runme();
return 0;
}
5. Virtual Functions
Definition:
“A function defined with virtual keyword in the base class is known
as virtual function. Compiler will decide the exact class pointed to, by the
base class pointer and call the respective function of that class if the
function is defined as virtual‖.
Virtual table:
―A table consisting of pointers to all virtual functions of class, every
class with atleast one virtual function will have one copy of virtual table‖.
Virtual Destructors
The issue of more unreferenced memory blocks is solved by virtual
destructors.
Syntax
class shape
{
public:
virtual ~shape( ){………} //virtual destructors
};
Rules for virtual function:
Functions name must be proceeded by virtual keyword in the base
class.
Virtual constructors are not possible. Constructing a derived class
object needs specific construction of the base class sub object
within.
The function in the derived class must have same name as of the
virtual function defined in the base class and the same prototype.
#include<iostream.h>
#include<conio.h>
using namespace std;
class Shape
{
public:
virtual void Draw()
{
cout<<"\n Shape is drawn:";
}
};
ptrs=&s;
ptrs->Draw( ); //calling base class draw
function
ptrs=&c;
ptrs->Draw( ); //calling derived class draw
function
Output:
Shape is drawn
Circle is drawn
Constructors:
―A constructor is a special member function whose task is to initialize the
objects of its class. It is special because its name is same as class name.
The constructor of a class is the first member function to be executed
automatically when an object of the class is created”.
Syntax:
Class classname
{
Public:
Classname( ); //constructor prototype
}
Classname :: classname( )
{
//constructor body definition
}
Example:
class integer
{
int m,n;
public:
integer(void); // constructor invoked
………
………
};
integer: :integer(void) //constructor defined
{
m=0,n=0;
}
21. What is the need of object initialization? State the various rules for
defining constructor. [May/Jun 2013]
Need For Object Initialization
return 0;
}
OUTPUT
id of A : 100
id of B : 100
id of C : 100.
id of D : 100
public:
int Hours;
int Minutes;
int Seconds;
void ShowTime( )
{
cout<<‖Time is ―<<Hours<<‖Hours : ―<<Minutes<<‖Minutes: and
―<<Seconds<<‖Seconds \n‖;
}
Time ( ) { }
Time (int TempHours, int TempMinutes=0, int TempSeconds=0)
{
Hours=TempHours;
Minutes=TempMinutes;
Seconds=TempSeconds;
}
};
void main ( )
{
Time Time1 (12, 15, 15);
cout<<‖The Time Number 1 \n‖;
Time1.showtime ( );
Time Time2 (10, 30);
cout<<‖The Time Number 2 \n‖;
Time2.showtime ( );
Time Time3;
Time3 = Time (12);
cout<<‖The Time Number 3 \n‖;
Time3.showtime ( );
Time Time4 = 12;
cout<<‖The Time Number 4 \n‖;
Time4.showtime ( );
}
Note:
In object declaration we must pass initial values as arguments to the
constructor function either in the following two ways:
By calling the constructor explicitly.
By calling the constructor implicitly.
EXPLICIT CALL
Example: integer int1=integer (0,100);
IMPLICIT CALL
Example: integer int1 (0,100);
PROGRAM:
#include <iostream>
using namespace std;
class integer
{
int m,n;
public:
integer(int,int);
void display(void)
{
cout<<"m="<<m<<"\n";
cout<<"n="<<n<<"\n";
}
};
integer::integer (int x, int y) // constructor defined
{
m=x, n=y;
}
int main()
{
integer int1(0,100); // constructor called implicitly
integer int2=integer(25,75); //constructor called explicitly
cout<<"\n OBJECT1"<<"\n";
int1.display();
cout<<"\nOBJECT2"<<"\n";
int2.display();
return 0;
}
Output:
OBJECT1
m=0
n=100
OBJECT2
m=25
n=75
25. Explain constructor with dynamic allocation using suitable C++
coding.
Definition ―Constructor uses new to allocate memory for objects at the time
of creation which is common to only when the objects are of varied size and
the size is available only at run time." Such constructors are referred as
constructor with dynamic allocation."
Note
Object initialization can be done either at the compile time or at run
time.
Also we can reinitialize an object created at compile time or
We can create an object and initialize it at runtime.
PROGRAM
//DynamicMem Alloc.cpp
#include<iostream.h>
#include<string.h>
#include<conio.h>
class string
{
char *name;
int length;
public:
string()
{
length=0;
name=new char[length+1];
}
string(char*s)
{
length=strlen(s);
name=new char[length+1];
strcpy(name,s);
}
void display(void)
{
cout<<name<<"\n";
}
void join(string &a,string &b);
};
void string::join(string &a,string&b)
{
length=a.length+b.length;
delete name;
name=new char[length+1];
strcpy(name,a.name);
strcat(name,b.name);
};
void main()
{
clrscr();
string name1("object");
string name2("oriented");
string name3("programming lab");
string s1,s2;
s1.join(name1,name2);
s2.join(s1,name3);
name1.display();
name2.display();
s1.display();
s2.display();
getch();
}
OUTPUT
Enter Main
No of objects created 1
No of objects created 2
No of objects created 3
No of objects created 4
Enter Block 1
No of objects created 5
No of objects destroyed 5
Enter Block 2
No of objects created 5
No of objects destroyed 5
Re-Enter Main
No of Objects destroyed 4
No of Objects destroyed 3
No of Objects destroyed 2
No of Objects destroyed 1
27. Write a C++ program that will ask for a temperature in Fahrenheit
and display it
ALGORITHM:
Step 1: Start the program
Step 2: the program should prompt the user to enter the temperature value
to convert.
Step 3: Finally, display the converted value.
Step 4: Depending on the choice, use the following formulas.
Step 5: Formula to convert from Celsius to Fahrenheit: ((9/5)*degC)+32.
Step 6: Formula to convert from Fahrenheit to Celsius: 5*(degF-32)/9
Step 7: The process must continue until the user enters the option to quit
the program.
Step 8: You must create two separate functions for the temperature
conversion.
Step 9: one for the Celsius-to-Fahrenheit conversion and another one for the
Fahrenheit-to-Celsius conversion.
Step 10: end of the program.
PROGRAM:
#include <iostream>
using namespace std;
int main()
{
int ftemp;
int ctemp;
int select = 0;
cout << "Please select from the following: " << endl;
cout << "1) Fahrenheit-to-Celsius" << endl;
cout << "2) Celsius-to-Fahrenheit" << endl << endl;
cout << "Enter: ";
cin >> select;
if (select == 1)
{
cout << " Enter temperature in Fahrenheit to convert to degrees Celsius: ";
cin >> ftemp;
ctemp = (ftemp-32) * 5 / 9;
cout << "Equivalent in Celsius is: " << ctemp << endl;
}
else if (select == 2)
{
cout <<" Enter temperature in Celsius to convert to degrees Fahrenheit: ";
cin >> ctemp;
ftemp = ctemp*9/5 + 32;
cout << "Equivalent in Fahrenheit is: " << ftemp << endl;
}
else
cout << "Valid options 1 or 2." << endl;
return 0;
}
28. Write a C++ program that inputs two numbers and output the
largest number using Class. [ Nov/Dec 2009]
ALGORITHM:
Step 1: Start the program
Step 2: define a class as large
29. Write a C++ program to multiply two matrices and print the result.
[April/May 2010]
# include<iostream.h>
main ( )
{
int a [3] [3], b [3] [3], c [3] [3], i,j,k;
for (i=0;i<3;i++)
for (j=0;j<3;j++)
{
Cin>>a[i][j];
Cin>>b[i][j];
}
for (k=0;k<3;k++)
{
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
for (i=0;i<3;i++)
for (j=0;j<3;j++)
cout<<c[i][j];
}
#include<iostream.h>
#include<conio.h>
class student
char name[20];
int no;
public:
void insert()
cin>>name>>no;
void display()
cout<<‖\nName:—>‖<<name<<endl
<<‖\nEntryno:—>‖<<no<<endl;
};
int m1,m2,m3;
public:
void get()
insert();
cin>>m1>>m2>>m3;
void put()
display();
int total;
total=m1+m2+m3;
cout<<‖\n\n\tMarks1:‖<<m1<<endl
<<‖\n\tMarks2:‖<<m2<<endl
<<‖\n\tMarks3:‖<<m3<<endl
<<‖\t————‖<<endl
<<‖\tTotal :‖<<total<<endl;
};
public:
};
public:
void input()
put();
cout<<‖\n\nGrades to Match‖<<endl
<<‖*-*-*-*-*-*-*-*-*‖<<endl
};
void main()
awards obj;
clrscr();
obj.get();
obj.input();
getch();
PROGRAM:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::setprecision;
int main()
{
double radius(0.0);
cout << endl << "Enter radius: ";
double length(0.0);
cout << "Enter length: ";
cin >> length;
double width(0.0);
cout << "Enter width: ";
cin >> width;
cout << endl << "Area of circle is: " << setprecision(5) << Area(radius)
<< endl << "Area of square is: " << setprecision(5) << Area(length, width)
<< endl;
system("PAUSE");
return 0;
}
PROGRAM:
class Big
{
private:
int a;
int b;
public:
void show()
{
cout<<"enter the a and b value";
cin<<a<<b;
if(a>b)
cout<<"a is largest";
else
cout<<"b is largest";
}
};
void main()
{
Big n;
n.show();
}
ii) Write a C++ program that takes either two integers or two floating
point numbers and outputs the smallest using class friend function and
function overloading
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the class name as Base with data members and member
functions.
STEP 3: The function get() is used to read the 2 inputs from the user.
STEP 4: Declare the friend function mean(base ob) inside the class.
STEP 5: Outside the class to define the friend function and do the following.
STEP 6: Return the mean value (ob.val1+ob.val2)/2 as a float.
STEP 7: Stop the program.
PROGRAM:
#include<iostream.h>
#include<conio.h>
class base
{
int val1,val2;
public:
void get()
{
cout<<"Enter two values:";
cin>>val1>>val2;
}
friend float mean(base ob);
};
float mean(base ob)
{
return float(ob.val1+ob.val2)/2;
}
void main()
{
clrscr();
base obj;
obj.get();
cout<<"\n Mean value is : "<<mean(obj);
getch();
}
Output:
Enter two values: 10, 20
Mean Value is: 15
33. Illustrate the concept of function overloading to find the Maximum
of two numbers. [Nov/Dec 2011]
#include<iostream.h>
#include<conio.h>
class over
{
public:
int get(int,int);
float get(float,float);
};
int over::get(int a,int b)
{
if(a>b)
return a;
else
return b;
}
float over::get(float a,float b)
{
if(a>b)
return a;
else
return b;
}
void main()
{
int n1,n2,t;
float x,y,temp;
over obj;
clrscr();
cout<<‖\nEnter two integer number: ―;
cin>>n1>>n2;
t=obj.get(n1,n2);
cout<<‖Maximum number is: ―<<t;
cout<<‖\nEnter two float number: ―;
cin>>x>>y;
temp=obj.get(x,y);
cout<<‖Maximum number is: ―<<temp;
getch();
}
34. Write a C++ program to define overload constructor to perform
string initialization, string copy and string destructions. [May/Jun
2012]
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 50
class string
{
char str[MAX];
public:
friend void operator>>(istream &din,string &s1)
{
din>>s1.str;
}
string()
{
strcpy(str,‖ ―);
}
string(char s[])
{
strcpy(str,s);
}
};
}
}
void string::operator~()
{
strrev(str);
cout<<‖\n\nReverse of string is: ―<<str;
}
void string::operator!()
{
string temp;
strcpy(temp.str,str);
strrev(str);
if(strcmp(temp.str,str))
cout<<‖\n\nString is not palindrome.‖;
else
cout<<‖\n\nString is palindrome.‖;
}
void main()
{
string s1,s2;
int choice;
char ans;
clrscr();
cout<<‖\n\n **** STRING OPERATIONS ****‖;
do
{
cout<<‖\n\nÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
‖;
cout<<‖\n\n MENU:‖;
cout<<‖\n\n\t1.Concatination of string\n\n\t2.Equality\n\n\t3.Copy
string\n\n\t4.Reverse of string\n\n\t5.Palindrome\n\n\t6.Occurance of
substring‖;
cout<<‖\n\nÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
‖;
cout<<‖\n\nEnter your choice: ―;
cin>>choice;
switch(choice)
{
case 1:
cout<<‖\n\nEnter the first string: ―;
cin>>s1;
cout<<‖\n\nEnter the second string: ―;
cin>>s2;
s1+=s2;
break;
case 2:
cout<<‖\n\nEnter the first string: ―;
cin>>s1;
cout<<‖\n\nEnter the second string: ―;
cin>>s2;
s1==s2;
break;
case 3:
cout<<‖\n\nEnter the string: ―;
cin>>s1;
s2=s1;
break;
case 4:
cout<<‖\n\nEnter the string: ―;
cin>>s1;
~s1;
break;
case 5:
cout<<‖\n\nEnter the string: ―;
cin>>s1;
!s1;
break;
case 6:
cout<<‖\n\nEnter the string: ―;
cin>>s1;
cout<<‖\n\nEnter the string which you want to check for occurance: ―;
cin>>s2;
s1^s2;
break;
default:
cout<<‖\n\nPlease enter correct choice.‖;
break;
}
cout<<‖\n\n\nDo you want to continue?(y/n): ―;
flushall();
cin>>ans;
}while(ans==‘y‘ || ans==‘Y');
getch();
}
#include <iostream.h>
class fibonacci
{
private:
unsigned long int f0,f1,fib,
public:
fibonacci()
{
f0=0;
f1=1;
fib=f0+f1;
}
fibonacci (fibonacci &ptr)
{
f0=ptr.f0;
f1=ptr.f1;
fib=ptr.fib;
}
void increment()
{
f0=f1;
f1=fib;
fib=f0+f1;
}
void display()
{
cout << fib << 't\';
}
}; //end of class construction
void main (void)
{
fibonacci number;
for (int i=0; i<=15;i++)
{
number.display();
number.increment();
}
}
36. Write a C++ program to implement Dynamic memory allocation.
[Nov/Dec 2012]
#include<iostream.h>
#include<string.h>
#include<conio.h>
class string
{
char *name;
int length;
public:
string()
{
length=0;
name=new char[length+1];
}
string(char*s)
{
length=strlen(s);
name=new char[length+1];
strcpy(name,s);
}
void display(void)
{
cout<<name<<"\n";
}
void join(string &a,string &b);
};
void string::join(string &a,string&b)
{
length=a.length+b.length;
delete name;
name=new char[length+1];
strcpy(name,a.name);
strcat(name,b.name);
};
void main()
{
clrscr();
string name1("object");
string name2("oriented");
string name3("programming lab");
string s1,s2;
s1.join(name1,name2);
s2.join(s1,name3);
name1.display();
name2.display();
s1.display();
s2.display();
getch();
}
PART – B
14. Write a C++ program to list out prime numbers between the
given two limits. [Nov/Dec 2013]
Refer Q-No: