subject: object oriented programming with · pdf filesubject: object oriented programming with...
TRANSCRIPT
SUBJECT: OBJECT ORIENTED PROGRAMMING WITH C++
QUESTION BANK SOLUTION
Q-1) Explain basic concepts of Object Oriented Programming (7 marks).
Ans: It is necessary to understand some of the concepts used extensively in object-oriented
programming. These include:
• Objects
• Classes
• Data abstraction and encapsulation
• Inheritance
• Polymorphism
1) OBJECT: Objects are the basic run time entities in an object-oriented system. They
may represent a person, a place, a bank account, a table of data or any item that the
program has to handle. They may also represent user-defined data such as vectors,
time and lists.
2) CLASSES: We just mentioned that objects contain data, and code to manipulate that
data. The entire set of data and code of an object can be made a user-defined data
type with the help of class. In fact, objects are variables of the type class. Fruit
Mango; will create an object mango belonging to the class fruit.
3) DATA ABSTRACTION AND DATA HANDLING: The wrapping up of data and
function into a single unit (called class) is known as encapsulation. Data and
encapsulation is the most striking feature of a class. The data is not accessible to the
outside world, and only those functions which are wrapped in the class can access it.
These functions provide the interface between the object‟s data and the program.
This insulation of the data from direct access by the program is called data hiding or
information hiding. The attributes are sometime called data members because they
hold information. The functions that operate on these data are sometimes called
methods or member function.
4) INHERITANCE: Inheritance is the process by which objects of one class acquired
the properties of objects of another classes. It supports the concept of hierarchical
classification. For example, the bird, „robin‟ is a part of class „flying bird‟ which is
again a part of the class „bird‟.
5) POLYMORPHISM: Polymorphism is another important OOP concept.
Polymorphism, a Greek term, means the ability to take more than on form. An
operation may exhibit different behaviour is different instances. The behaviour
depends upon the types of data used in the operation. For example, consider the
operation of addition. For two numbers, the operation will generate a sum. If the
operands are strings, then the operation would produce a third string by
concatenation. The process of making an operator to exhibit different behaviours in
different instances is known as operator overloading.
Q-2) Explain This Pointer (3 Marks).
Ans: Every object in C++ has access to its own address through an important pointer called
“this” pointer. The “this” pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to invoking object.
Friend function do not have a this pointer, because friends are not member of a class.
Only member functions have a “this” pointer.
Q-3) Define function overloading with proper example (3 Marks).
Ans: If any class have multiple functions with same names but different parameters then they
are said to be overloaded. Function overloading allows you to use the same name for
different functions, to perform, either same or different functions in the same class.
Function overloading is usually used to enhance the readability of the program. If you
have to perform one single operation but with different number or types of arguments,
then you can simply overload the function.
#include<iostream.h>
#include<conio.h>
void repchar( )
{
for(int i=0; i<3; i++)
{
cout<<”#”;
}
}
void repchar(char ch)
{
for(int i=0; i<3; i++)
{
cout<<ch;
}
}
void repchar(char ch , int n)
{
for(int i=0; i<n; i++)
{
cout<<ch;
}
}
void main( )
{
clrscr( );
repchar( );
repchar(„+‟);
repchar(„@‟,3);
getch( );
}
OUTPUT:
# # #
+ + +
@ @ @
Q-4) what is inline function? In which situation inline function may not
work? How does an inline function differ from a pre-processor macro?
Write a program to fine maximum out of three using inline function
(7 Marks).
Ans: C++ inline function is powerful concept that is commonly used with classes. If a
function is inline, the compiler places a copy of the code of that function at each point
where the function is called at compile time. To inline a function, place the
keyword inline before the function name and define the function before any calls are
made to the function. The compiler can ignore the inline qualifier in case defined
function is more than a line.
Some of the situation where inline function may not work.
For function returning values, if a Loop, Switch or Goto statement exist.
If function contains static variable.
If inline function is recursive.
The major difference between inline function and Macro is the way they are handled.
Inline functions are parsed by the compiler whereas the Macros are expanded by the
Pre-processor.
#include<iostream.h>
#include<conio.h>
inline int big(int a,int b,int c)
{
if(a>b)
{
if(a>c)
{
return a;
}
else
{
return c;
}
}
else
{
if(b>c)
{
return b;
}
else
{
return c;
}
}
}
void main()
{
clrscr();
int i,j,k;
cout<<”Enter three nos = “;
cin>>a>>b>>c;
cout<<”Ans = “<<big(a,b,c);
getch();
}
OUTPUT:
Enter three nos : 2 4 5
Ans = 5
Q-5) What is reference variable? What is its major use? Give Example
(4 Marks).
Ans: A reference variable is an alias, that is, another name for an already existing variable.
Once a reference is initialized with a variable, either the variable name or the reference
name may be used to refer to the variable. References are usually used for function
argument lists and function return values. So following are two important subjects
related to C++ references which should be clear to a C++ programmer:
Concept Description
References as parameters C++ supports passing references as function parameter
more safely than parameters.
Reference as return value
You can return reference from a C++ function like an
any other data type can be returned.
#include <iostream.h>
#include <conio.h>
void main ()
{
// declare simple variables
int i;
double d;
// declare reference variables
int& r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
OUTPUT:
Value of i: 10
Value of i reference: 10
Value of d: 5
Value of d reference: 5
Q-6) Explain the default argument with example (4 marks).
Ans: In C++ programming, you can provide default values for function parameters. The idea
behind default argument is very simple. If a function is called by passing argument/s, those
arguments are used by the function. But if all argument/s are not passed while invoking a
function then, the default value passed to arguments are used. Default value/s is passed to
argument/s in function prototype.
#include <iostream.h>
#include <conio.h>
void display(char c = „*‟, int n = 1)
{
for(int i = 1; i <=n; ++i)
{
cout<<c;
}
cout<<endl;
}
void main( )
{
cout<<"No argument passed:\n";
display ( );
cout<<"\n\nFirst argument passed:\n";
display('#');
cout<<"\n\nBoth arguments passed:\n";
display('$', 5);
getch();
}
OUTPUT:
No argument passed:
*
First argument passed:
#
Both arguments passed:
$$$$$
Q-7) What is constructor? Which are the special characteristics of
constructor function? What is the need of “do-nothing” implicit
constructor? When the destructor function invoked? (7 Marks).
Ans: Constructors are special class functions which performs initialization of every object. The
Compiler calls the Constructor whenever an object is created. Constructors initialize values
to object members after storage is allocated to the object. class ASHISH
{
int x;
public:
ASHISH( ); //Constructor
{
cout<<”I am constructor”;
}
};
void main( )
{
clrscr( );
ASHISH A1( ); //do-nothing implicit constructor.
getch( );
}
While defining a contructor you must remember that the name of constructor will be same
as the name of the class, and contructors never have return type.
Characteristics of Constructor:
Constructors have the same name as that of the class they belong to.
Constructors are executed when an object is declared.
Constructors have neither return value nor void.
The main function of constructor is to initialize objects and allocate
appropriate memory to objects.
Though constructors are executed implicitly, they can be invoked explicitly.
Constructors can have default values and can be overloaded.
The constructor without arguments is called as default constructor (do nothing
implicit).
Destructor is a special class function which destroys the object as soon as the scope of
object ends. The destructor is called automatically by the compiler when the object
goes out of scope. The syntax for destructor is same as that for the constructor, the class
name is used for the name of destructor with a tilde ~ sign as prefix to it.
class ASHISH
{
public:
ASHISH( )
{
cout<<”I am Constructor”;
}
~ASHISH( )
{
cout<<”I am Destructor”;
}
};
void main( )
{
clrscr( );
ASHISH A1;
getch( );
}
OUTPUT:
I am Constructor
I am Destructor
Q-8) What is type conversion? Explain basic to class type and class type to
basic type conversion with example. (7 Marks).
Ans: Type conversion (often a result of type casting) refers to changing an entity of one data
type, expression, function argument, or return value into another. This is done to take
advantage of certain features of type hierarchies. For instance, values from a more limited
set, such as integers, can be stored in a more compact format and later converted to a
different format enabling operations not previously possible, such as division with several
decimal places' worth of accuracy. In the object-oriented programming paradigm, type
conversion allows programs also to treat objects of one type as one of another. One must do
it carefully as type casting can lead to loss of data.
#include<iostream.h>
#include<conio.h>
const float MTF = 3.24;
class distance
{
int feet;
float inch;
public:
distance()
{
feet = 0;
inch = 0.0;
}
distance(float meters)
{
float fltfeet = MTF * meters;
feet = int (fltfeet);
inch = 12 * (fltfeet - feet);
}
distance(int ft,float in)
{
feet = ft;
inch = in;
}
void getdist()
{
cout<<"\nEnter feet : ";
cin>>feet;
cout<<"\nEnter Inch : ";
cin>>inch;
}
void showdist()
{
cout<<feet<<" "<<inch;
}
operator float()
{
float fracfeet = inch / 12;
fracfeet += float(feet);
return fracfeet / MTF;
}
};
void main()
{
clrscr();
distance dist1 = 2.00;
cout<<"\nDist1 = ";
dist1.showdist();
dist1 = 1.00; //basic type to class type conversion
cout<<"\nDist1 = ";
dist1.showdist();
distance dist2(5,10.00);
float mtrs = float (dist2); //Class type to basic type conversion
cout<<"\nDist2 = "<<mtrs<<" meters";
mtrs = dist1;
cout<<"\nDist1 = "<<mtrs<<" meters";
getch();
}
Basic to type class conversion
function
Class type to Basic type conversion
Q-9) Explain new and delete operator. What are the advantages of new
operator over malloc? OR Explain memory management operator. (4
Marks)
Ans: Arrays can be used to store multiple homogenous data but there are serious
drawbacks of using arrays. Programmer should allocate the memory of an
array when they declare it but most of time, the exact memory needed cannot
be determined until runtime. The best thing to do in this situation is to declare
the array with maximum possible memory required (declare array with
maximum possible size expected) but this wastes memory. To avoid wastage
of memory, you can dynamically allocate the memory required during runtime
using new and delete operator.
Advantages of new operator over malloc function:
It automatically computes the size of data object. We need not use the
operator sizeof();
It automatically returns the current pointer type so there is no need to
type cast.
Like any other operator new and delete can be overloaded.
It is possible to initialize the object while allocating the memory.
Syntax of new operator:
type *PointerVariableName;
PointerVariableName = new type [size];
For variable:
int n;
cout<<”Enter total size = “;
cin>>n;
int *m;
m = new int[n];
For object:
int n;
cout<<”Enter total size = “;
cin>>n;
className *m;
m = new className[n];
Syntax of delete operator:
delete pointerVariableName; Ex: delete m;
&
delete [ ]pointerVariableName; Ex: delete [ ]m;
Q-10) Explain scope resolution operator with example.(3 Marks)
Ans: The :: (scope resolution) operator is used to qualify hidden names so that you can still use
them. You can use the unary scope operator if a namespace scope or global scope name is
hidden by an explicit declaration of the same name in a block or class. For example:
class XYZ
{
int x,y,z;
public:
void getdata( );
void display( );
};
void XYZ :: getdata( )
{
Cout<<”Enter value of X, Y and Z = “;
Cin>>x>>y>>z;
}
void XYZ :: display( )
{
cout<<”X=”<<x<<endl;
cout<<”Y=”<<y<<endl;
cout<<”Z=”<<z<<endl;
}
void main( )
{
Clrscr( );
XYZ X1;
X1.getdata( );
X1.display( );
getch( );
}
Q-11) How do they differ? char const *ptr , char *const ptr.(3 Marks)
Ans: const char *p - This is a pointer to a constant character. You cannot change the value
pointed by p, but you can change the pointer p itself.
*p = 'S' is illegal.
p = "Test" is legal.
Note - char const *p is the same.
const * char p - This is a constant pointer to non-constant character. You cannot
change the pointer p, but can change the value pointed by p.
*p = 'A' is legal.
p = "Hello" is illegal.
Q-12) what is polymorphism? What is the Difference between runtime and
compile time polymorphism. Explain and demonstrate, how virtual
function to achieve runtime polymorphism. (7 Marks)
Ans: Polymorphism is another important OOP concept. Polymorphism, a Greek term, means
the ability to take more than on form. An operation may exhibit different behaviour is
different instances. The behaviour depends upon the types of data used in the operation.
For example, consider the operation of addition. For two numbers, the operation will
generate a sum. If the operands are strings, then the operation would produce a third
string by concatenation. The process of making an operator to exhibit different
behaviours in different instances is known as operator overloading.
Real life example of polymorphism
Suppose if you are in class room that time you behave like a student, when you are in
market at that time you behave like a customer, when you at your home at that time
you behave like a son or daughter, Here one person have different-different
behaviours.
Types of polymorphism
1. Compile time polymorphism
2. Runtime polymorphism
1. Compile time polymorphism
In C++ programming you can achieve compile time polymorphism in two way, which
is given below;
Method overloading or Function overloading.
Method overriding or Function overriding.
Example of Method overloading: refer Question no 3 solution in this document.
Example of Method overriding:
#include <iostream.h>
#include <conio.h>
class base
{
Public:
Void display( )
{
Cout<<”Base class”;
}
};
Class derived : public base
{
Public:
Void display( )
{
base :: display( );
cout<<”derived class”;
}
};
Void main( )
{
Clrscr( );
derived d1;
d1.display( );
getch( );
}
OUTPUT:
Base class derived class
2. Runtime polymorphism
In C++, runtime polymorphism can be achieved by using virtual function.
A virtual function is a member function of class that is declared within a base
class and re-defined in derived class. When you want to use same function name in
both the base and derived class, then the function in base class is declared as
virtual by using the virtual keyword and again re-defined this function in derived
class without using virtual keyword.
Syntax:
virtual type functionName( arguments )
{
///Code///
}
Example:
#include <iostream.h>
#include <conio.h>
class base
{
Public:
virtual void display( )
{
Cout<<”Base class”;
}
};
Class derived : public base
{
Public:
Void display( )
{
base :: display( );
cout<<”derived class”;
}
};
Void main( )
{
Clrscr( );
base *b;
derived d1;
b = &d1;
d1 display( );
getch( );
}
OUTPUT:
derived class
Q-13) what is copy constructor? Give its use. When it is used implicitly for
what purpose? (7 Marks)
Ans: The copy constructor is a constructor which creates an object by initializing it with an
object of the same class, which has been created previously. The copy constructor is
used to:
Initialize one object from another of the same type.
Copy an object to pass it as an argument to a function.
Copy an object to return it from a function.
If a copy constructor is not defined in a class, the compiler itself defines one. If the
class as pointer variables and has some dynamic memory allocations, then it is a must
to have a copy constructor. The most common form of copy constructor is shown here:
classname (const classname &obj)
{ // body of constructor
}
Example:
#include<iostream.h>
#include<conio.h>
class base
{
int a,b;
public:
base()
{
cout<<"Enter values = ";
cin>>a>>b;
}
void display()
{
cout<<endl<<"A = "<<a<<endl<<"B = "<<b<<endl;
}
base(const base &b1)
{
a = b1.a;
b = b1.b;
}
};
void main()
{
clrscr();
base b1;
base b2(b1);
cout<<"Object 1 values";
b1.display();
cout<<"Object 2 values";
b2.display();
getch();
}
OUTPUT:
Enter values = 1 3
Object 1 values
A = 1
B = 3
Object 2 values
A = 1
B = 3
Q-14) what is the use of friend function? Write characteristics of friend
function and also explain with proper example. (7 Marks)
Ans: A friend function of a class is defined outside that class' scope but it has the right to
access all private and protected members of the class. Even though the prototypes for
friend functions appear in the class definition, friends are not member functions. A
friend can be a function, function template, or member function, or a class or class
template, in which case the entire class and all of its members are friends. To declare a
function as a friend of a class, precede the function prototype in the class definition
with keyword friend.
Characteristics of friend functions
A friend function is not in the scope of the class, in which it has been declared as
friend.
It cannot be called using the object of that class.
It can be invoked like a normal function without any object.
Unlike member functions, it cannot use the member names directly.
It can be declared in public or private part without affecting its meaning.
Usually, it has objects as arguments.
Example:
#include <iostream.h>
#include <conio.h>
Class B;
Class A
{
int a;
public:
void get_a( )
{
Cout<<”Enter value of a = “;
Cin>>a;
}
friend void sum(A,B);
};
Class B
{
int b;
public:
void get_b( )
{
Cout<<”Enter value of b = “;
Cin>>b;
}
friend void sum(A,B);
};
Void sum (A obj1, B obj2)
{
int c;
c = obj1.a + obj2.b;
cout<<”Ans = “<<c;
}
Void main( )
{
Clrscr( );
A Obj1;
B Obj2;
Obj1.get_a( );
Obj2.get_b( );
sum(obj1,obj2);
getch( );
}
Q-15) what is stream? Describe various stream classes for console I/O
operations. (7 Marks)
The first thing you may notice about this hierarchy is that it uses multiple inheritances
(that thing we told you to avoid if at all possible). However, the iostream library has
been designed and extensively tested in order to avoid any of the typical multiple
inheritance problems, so you can use it freely without worrying.
Streams
The second thing you may notice is that the word “stream” is used an awful lot. At its
most basic, I/O in C++ is implemented with streams. Abstractly, a stream is just a
sequence of characters that can be accessed sequentially. Over time, a stream may
produce or consume potentially unlimited amounts of data. Typically we deal with two
different types of streams. Input streams are used to hold input from a data producer,
such as a keyboard, a file, or a network. For example, the user may press a key on the
keyboard while the program is currently not expecting any input. Rather than ignore the
users key press, the data is put into an input stream, where it will wait until the program
is ready for it. Conversely, output streams are used to hold output for a particular data
consumer, such as a monitor, a file, or a printer. When writing data to an output device,
the device may not be ready to accept that data yet -- for example, the printer may still
be warming up when the program writes data to its output stream. The data will sit in
the output stream until the printer begins consuming it. Some devices, such as files and
networks, are capable of being both input and output sources.
Input/output in C++
Although the ios class is generally derived from ios_base, ios is typically the most base
class you will be working directly with. The ios class defines a bunch of stuff that is
common to both input and output streams. We‟ll deal with this stuff in a future lesson.
The istream class is the primary class used when dealing with input streams. With
input streams, the extraction operator (>>) is used to remove values from the stream.
This makes sense: when the user presses a key on the keyboard, the key code is placed
in an input stream. Your program then extracts the value from the stream so it can be
used.
The ostream class is the primary class used when dealing with output streams. With
output streams, the insertion operator (<<) is used to put values in the stream. This
also makes sense: you insert your values into the stream, and the data consumer (eg.
monitor) uses them.
The iostream class can handle both input and output, allowing bidirectional I/O.
Finally, there are a bunch of classes that end in “_withassign”. These stream classes are
derived from istream, ostream, and iostream (respectively) with an assignment operator
defined, allowing you to assign one stream to another. In most cases, you won‟t be
dealing with these classes directly.
Standard streams in C++
A standard stream is a pre-connected stream provided to a computer program by its
environment. C++ comes with four predefined standard stream objects that have
already been set up for your use. The first two, you have seen before:
cin -- an istream_withassign class tied to the standard input (typically the
keyboard)
cout -- an ostream_withassign class tied to the standard output (typically the
monitor)
cerr -- an ostream_withassign class tied to the standard error (typically the
monitor), providing unbuffered output
clog -- an ostream_withassign class tied to the standard error (typically the
monitor), providing buffered output
Q-16) Explain file pointers and functions for their manipulator. (7 Marks)
Ans: All file objects hold two file pointers that are associated with the file. These two file
pointers provide two integer values. These integer values indicate the exact position of the file pointers in the number of bytes in the file. The read or write operations are carried out at the location pointed by these file pointers .One of them is called get pointer (input pointer), and the second one is called put pointer (output pointer). During reading and writing operations with files, these file pointers are shifted from one location to another in the file. The (input) get pointer helps in reading the file from the given location, and the output pointer helps in writing data in the file at the specified location. When read and write operations are carried out, the respective pointer is moved.
Read mode:
When a file is opened in read mode, the get pointer is set at the beginning of the file.
Hence, it is possible to read the file from the first character of the file.
Write Mode:
When a file is opened in write mode, the put pointer is set at the beginning of the file,
thus, it allows the write operation from the beginning of the file. In case the specified
file already exists, its contents will be deleted.
Append Mode:
This mode allows the addition of data at the end of the file. When the file is opened in
append mode, the output pointer is set at the end of the file. Hence, it is possible to
write data at the end of the file. In case the specified file already exists, a new file is
created, and the output is set at the beginning of the file. When a pre-existing file is
successfully opened in append mode, its contents remain safe and new data are
appended at the end of the file.
Sometimes you may have to manipulate file pointers to read from and write to a
particular location in a file. The seekg() and tellg() functions allow you to set and
examine the get pointer, and the seekp() and tellp() functions perform these same
actions on the put pointer. In other words, these four functions allow you to access the
file in a non-sequential or random mode.
All the iostream clas objects can be repositioned by using either the seekg() or the
seekp() member function. These functions move the get and put pointers respectively to
an absolute address within the file or toa certain number of bytes from a particular
position.
The tellg() and tellp() functions can be used to find out the current position of the get
and put file pointers respectively in a file.
The seekg() member function takes two arguments:
• Number of bytes to move.
• Reference in the file from which the pointer has to be repositioned.
For example:
If stream iFi1;
iFi1.seekg(10,ios:beg);
means, “position the get pointer 10 bytes from the beginning of the file”
The first argument is an integer that specifies the number of bytes positions(also called
offset). The second argument is the reference point. There are three reference points
defined in the ios class:
• ios:beg – the beginning of the file.
• ios:cur – the current position of the file pointer
• ios:end – the end of the file
A negative value can also be specified for the first argument. For example, the
following statement moves the file pointer 20 bytes backward from the end of the file.
iFi1.seekg(-20,ios:end);
If the seekg( ) function is used with only one argument, the ios:beg reference point is
assumed. For example in the statement:
iFi1.seekg(16);
ios:beg will be the reference point and hence the get pointer will be positioned 16 bytes
from the beginning of the file.
The tellg() member function does not have any arguments. It returns the current byte
position of the get pointer relative to the beginning of the file. For example the
statement:
intiPosition = iFi1.tellg();
will result in the variable iPosition having the value of the current position of the get
pointer.
The seekp() and tellp() member functions are identical to the above two functions, but
they are identified with the put pointer. The seekg() and tellg() member functions are
defined in the istream class. The seekp() and tellp() member functions are defined in the
istream class. The seekp() and tellp() member functions are defined in the ostream
class.
Q-17) What is inheritance? List the types of inheritance with figure.
(7 Marks)
Ans: Inheritance is the capability of one class to acquire properties and characteristics from
another class. The class whose properties are inherited by other class is called
the Parent or Base or Super class. And, the class which inherits properties of other
class is called Child or Derived or Sub class. Inheritance makes the code reusable.
When we inherit an existing class, all its methods and fields become available in the
new class, hence code is reused.
Purpose of Inheritance
1. Code Reusability
2. Method Overriding (Hence, Runtime Polymorphism.)
3. Use of Virtual Keyword
Basic Syntax of Inheritance
class Subclass_name : access_mode Superclass_name
{
//Code of derived class//
}
While defining a subclass like this, the super class must be already defined or at least
declared before the subclass declaration. Access Mode is used to specify, the mode in
which the properties of superclass will be inherited into subclass, public, private or
protected.
In C++, we have 5 different types of Inheritance. Namely,
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)
Single Inheritance
In this type of inheritance one derived class inherits from only one base class. It is the
simplest form of Inheritance.
Multiple Inheritance
In this type of inheritance a single derived class may inherit from two or more than
two base classes.
Hierarchical Inheritance
In this type of inheritance, multiple derived classes inherit from a single base class.
Multilevel Inheritance
In this type of inheritance the derived class inherits from a class, which in turn inherits
from some other class. The Super class for one is sub class for the other.
Hybrid (Virtual) Inheritance
Hybrid Inheritance is combination of all four inheritance (Single, Multiple,
Multilevel, Hierarchical).
Q-18) what is pointer to object? What is this pointer? Write a complete
program to illustrate the use of this pointer. (7 Marks)
Ans: Pointer to Object: A variable that holds an address value is called a pointer variable or
simply pointer. Pointer can point to objects as well as to simple data types and arrays.
Sometimes we don‟t know, at the time that we write the program, how many objects we
want to create. When this is the case we can use new to create objects while the
program is running. new returns a pointer to unnamed objects. Let‟s see the example of
student that will clear your idea about this topic.
#include <iostream.h>
#include <string.h>
class student
{
private:
int rollno;
string name;
public:
student():rollno(0),name("")
{}
student(int r, string n): rollno(r),name (n)
{}
void get()
{
cout<<"enter roll no";
cin>>rollno;
cout<<"enter name";
cin>>name;
}
void print()
{
cout<<"roll no is "<<rollno;
cout<<"name is "<<name;
}
};
void main ()
{
student *ps=new student;
(*ps).get();
(*ps).print();
delete ps;
}
This Pointer: Every object in C++ has access to its own address through an important
pointer called this pointer. The this pointer is an implicit parameter to all member
functions. Therefore, inside a member function, this may be used to refer to the
invoking object. Friend functions do not have a this pointer, because friends are not
members of a class. Only member functions have a this pointer. Let us try the
following example to understand the concept of this pointer:
#include<iostream.h>
#include<conio.h>
class ABC
{
int a,b;
public:
void setdata(int a,int b)
{
this a = a;
this b = b;
}
void display()
{
cout<<"A = "<<a<<"B = "<<b;
}
};
void main()
{
clrscr();
ABC A1;
A1.setdata(3,4);
A1.display();
getch();
}
Q-19) what is template? Explain with example. (7 Marks)
Ans: Templates are the foundation of generic programming, which involves writing code
in a way that is independent of any particular type. A template is a blueprint or formula
for creating a generic class or a function. The library containers like iterators and
algorithms are examples of generic programming and have been developed using
template concept. There is a single definition of each container, such as vector, but we
can define many different kinds of vectors for example, vector <int> or vector
<string>. You can use templates to define functions as well as classes, let us see how
they work:
Syntax:
template <class PlaceHolderName>
PlaceHolderName FunctionName (PlaceHolderName VariableName)
Example:
#include<iostream.h>
#include<conio.h>
template <class A>
A big(A a1,A a2)
{
if (a1>a2)
{
return a1;
}
else
{
return a2;
}
}
Void main()
{
Clrscr();
Cout<<”Ans = “<<big(2,3);
Cout<<”\nAns = “<<big(2.3,1.3);
Getch();
}
OUTPUT:
Ans = 3
Ans = 2.3