Académique Documents
Professionnel Documents
Culture Documents
COMPILED BY
M.KARTHIKEYAN, M.E., (AP/IT)
VERIFIED BY
HOD
PRINCIPAL
CORRESPONDENT
PART-B
1. Explain the various types of constructors that are available in C++ with suitable
example. (16m) [M/J2016] [8m] [A/M2015](16m)[M/J2012] (4m)[A/M2011] [or]
Describe the special characteristics of constructor function. (8m)[N/D2014] [or] Discuss
on Destructor.(4m) [M/J2013] (8m)[N/D2012] (8m)[N/D2011]
2. What is meant by polymorphism? Explain the various types of polymorphism in C++
with suitable examples. (16m) [A/M2015] (6m) [N/D2014] (4m) [M/J2013] (16m)
[N/D2013] (8m)[N/D2011] [or] What is meant by function overloading? Write a C++
program to illustrate the concept of function overloading. (16m)[M/J2012] (8m)
[N/D2012]
3. What is data hiding? What are the different mechanisms for protecting data from the
external uses of a classs objects? (16m) [M/J2014] (8m) [N/D2013]
4. Write short notes about iterators and containers. (8m)[N/D2014] (4m)[M/J2013] (8m)
[N/D2012] (8m) [N/D2013] (8m) [N/D2012] [or] Explain about object creation and
Iterators with example. (16m) [M/J2013]
5. Write a C++ program illustrating class declaration, definition and accessing class
members. (16m) [M/J2014]
6. Write a program to create a class employee with necessary data members and
methods. Create an array of objectives for employee class and print the pay slip for
employees. (10m) [N/D2014]
7. Explain array of objects with example in c++. [M/J2016] [8]
8. What is operator overloading in c++ ? List out the rules to overload a binary operator
[M/J2016][7]
9. Write a C++ program to add two vectors using + operators overloading.[M/J2016]
[9m]
NOTES
UNIT II
BASIC CHARACTERISTICS OF OOP
PART A
1. What is meant by data abstraction? [A/M2015] [M/J2013] [M/J2012] [N/D2013]
Abstraction refers to the act of representing essential features without including the
background details or explanation. Classes use the concept of abstraction and are
defined as a list of abstract attributes such as size, wait, and cost, and function operate
on these attributes. They encapsulate all the essential properties of the object that are
to be created.
2. What is the use of destructor ? [M/J2016] [OR] What is destructor? Illustrate
with an example. [A/M2015]
Destructor is used to destroy the objects that have been created by a constructor.
It is a member function, whose name is same as the class name preceded by a
tilde.
The destructor never takes any arguments nor does it return any value.
It will be invoked implicitly by the compiler upon exit from the program to clean up
storage.
E.g., ~integer ( ) { }
3. How are inline members functions defined outside the body of the class? Give
an example. [M/J2014]
The member function defined outside the class can be made inline by prefixing
the keyword inline to function declaration as shown below, example of an inline member
function defined outside the class body:
class Foo {
public:
5
void method(); // Best practice: Don't put the inline keyword here
// ...
};
inline void Foo::method() // Best practice: Put the inline keyword here
{
// ...
}
These are the functions designed to speed up program execution. An inline function is
expanded (i.e. the function code is replaced when a call to the inline function is made) in
the line where it is invoked.
4. Mention the types of polymorphism in C++. [M/J2014]
}
};
9. What is the general form of a class definition in C ++?
Class class_name
{
Private:
7
Variable declaration;
Function declaration;
Public:
Variable declarations;
Function declarations;
};
10. List out the important characteristics of constructor [N/D2012]
The constructor functions have some special characteristics. These are:
return values.
They cannot be inherited, though a derived class can call the base class
constructor.
Like other C++ functions, they can have default arguments.
Constructors cannot be Virtual.
An object with a constructor cannot be used as a member of union.
They make implicit calls to the operators new and delete when memory allocation
is required.
The private data of a class can be accessed only through the member functions
of that class. The format for calling a member function,
Objectname.function_name(actual _arguments);
14. What are the ways of passing objects as function arguments?
Pass by value: A copy of the entire object is passed to the function. Any changes made
to the object inside the function dont affect the objects used to call the function.
Pass by Reference: Only the address of the object is transferred to the function.
When an address of the object is passed, the called function works directly on the
actual object used in the call. This means that any changes made to the object inside
the function will reflect in the actual object.
15. Give the general form of an operator function.
The general form of an operator function is given as,
return-type class-name :: operator op (arglist)
{
function body
}
Where,
Return-type -> type of value returned
operator -> keyword
op -> operator being overloaded
16. What are reference variable?
A reference variable provides an alias(alternative name) for a previously defined
variable. Sum total For example, if make the variable a reference to the variable, then
sum and total can be used interchangeably to represent that variable.
Syntax:
Data-type &reference-name = variable-name
Eg:
9
Class A
{
--------public :
A(A &);
}
19. What are free store operators (or) Memory management operators?
10
New and Delete operators are called as free store operators since they allocate
the memory dynamically.
Initialization of the memory using new operator can be done. This can be done
as,
Pointer-variable = new data-type(value)
Delete operator is used to release the memory space for reuse. The general form
of its use is,
Delete pointer-variable;
1. Explain the various types of constructors that are available in C++ with suitable
example. (16m) [A/M2015](16m)[M/J2012] (4m)[A/M2011] [or] Describe the
special characteristics of constructor function. (8m)[N/D2014] [or] Discuss on
Destructor.(4m) [M/J2013] (8m)[N/D2012] (8m)[N/D2011]
Constructors(Dynamic initialization of objects)
To initialize a value to the variable, so far we have used the member functions.
By the member functions we cannot initialize a value for the variable at the time
of creation of an object.
Constructor is a special member function whose task is to initialize the objects of
its class. It is special because its name is the same as the class name.
The constructor is invoked whenever an object is created. A Constructor is
defined and declared as follows
Ex:
11
Class classname
{
Datamember declaration;
Public:
Classname()
{
}
Memberfunction definition;
};
class Sum
{
int a,b;
public:
Sum() //constructor definition
{
a=0;
b=0;
}
};
void main()
{
Sum ob; // Creation of object, it calls the
constructor
}
Once the object is created, the constructor will be called automatically, the values
are initialized to the variables. There is no need to write any statement to invoke the
constructor function. A constructor that has no arguments is called the default
constructor.
The constructor functions have some special characteristics. These are:
return values.
They cannot be inherited, though a derived class can call the base class
constructor.
Like other C++ functions, they can have default arguments.
Constructors cannot be Virtual.
An object with a constructor cannot be used as a member of union.
They make implicit calls to the operators new and delete when memory allocation
is required.
13
Explicit Call:
sample s=sample(10,20);
Implicit call:
sample s(10,20);
Ex:
class sample
{
int a,b;
public:
sample(int x,int y)
{
a=x;
b=y;
}
void disp()
{
int c;
c=a+b;
cout<<c;
}
};
Void main()
{
sample s(10,20);
s.disp();
}
Copy Constructor
A copy constructor is used to declare and initialize an object from another object. For
ex, the statement Sample ob(ob1); would define the object ob and at the same time
initialize it to the values of ob1. Another form of this statement is: sample ob1=ob; this
statement assigns the value of ob to ob1. This is the task of overloaded assignment
operator.
Ex:
class sample
void main()
{
14
{
int a,b,c;
public:
sample()
{
a=10;
b=20;
}
void disp()
{
c=a+b;
cout<<c<<"\n";
}
};
clrscr();
sample ob;
ob.disp();
sample ob1=ob;
ob1.disp();
getch();
}
Destructors
It is used to destroy the objects that have been created by a constructor. Like
constructor, the destructor is also a member function whose name is the same as
the class name but is preceded by the tilde. For ex, the destructor for the class
sample can be defined as shown below:
Characteristics of Destructors
A destructor never takes any argument nor does it return any value.
It will be invoked automatically by the compiler upon exit from the program.
A destructor is used to clean up storage that is no longer accessible.
15
Ex:
~sample()
class sample
cout<<"Objects destroyed:"<<a<<"\n";
public:
sample()
};
void main()
a++;
clrscr();
sample ob,ob1,ob2,ob3;
getch();
}
16
This means that we can use the same function name to create functions that
perform a variety of different tasks. This is known as function overloading.
A function call first matches the prototype having the same number and type of
arguments and then calls the appropriate function for execution. A best match
must be unique.
The compiler first tries to find an exact match in which the types of actual
arguments are the same, and use that function.
If an exact match is not found, the compiler uses the integral promotions to find
the match.
When either of them fails, the compiler tries to use the implicit conversions to the
actual arguments.
If all of the steps fail, then the compiler will try the user-defined conversions in
combination with integral promotions and built-in conversions to find a unique
match.
17
class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f)
{
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
int main(void)
{
printData pd;
// Call print to print integer
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
}
When the above code is compiled and executed, it produces the following result:
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
Operators overloading
You can redefine or overload most of the built-in operators available in C++. Thus
a programmer can use operators with user-defined types as well. Overloaded operators
are functions with special names the keyword operator followed by the symbol for the
operator being defined. Like any other function, an overloaded operator has a return
type and a parameter list.
Output:
Read first Complex Number
23
Read Second complex Number
22
The Complex Number is
4+i5
Dynamic Polymorphism or Run-Time Polymorphism
19
At runtime, when it is known what class objects are under consideration, the
appropriate version of the function is invoked. Since the functions is linked with a
particular class much later after the compilation, this process is termed as late
binding. It is also known as dynamic binding because the selection of the
appropriate function is done automatically at runtime.
Virtual function
A virtual function is a member function that is declared within a base class and
redefined by a derived class. To create virtual function, precede the functions
declaration in the base class with the keyword virtual. When a class containing
virtual function is inherited, the derived class redefines the virtual function to suit
its own needs.
Base class pointer can point to derived class object. In this case, using base
class pointer if we call some function which is in both classes, then base class
function is invoked. But if we want to invoke derived class function using base
class pointer, it can be achieved by defining the function as virtual in base class,
this is how virtual functions support runtime polymorphism.
Example:
Class A
{
int a;
public:
A()
{
a = 1;
}
virtual void show()
{
cout <<a;
}
};
Class B: public A
{
int b;
B()
{
b = 2;
}
virtual void show()
{
cout <<b;
}
};
int main()
{
A *pA;
B oB;
pA = &oB;
pA->show();
return 0;
20
public:
}
Output is 2 since pA points to object of B and show() is virtual in base class A.
Abstract Class
Abstract Class is a class which contains at least one Pure Virtual function in it.
Abstract classes are used to provide an Interface for its sub classes. Classes inheriting
an Abstract Class must provide definition to the pure virtual function; otherwise they will
also become abstract class.
Characteristics of Abstract Class
function.
Abstract classes are mainly used for Up casting, so that its derived classes can
int main()
public:
Base *b;
};
Derived d;
b = &d;
public:
b->show();
void show()
}
21
22
Example:
class Line
{
public:
double length;
void setLength( double len );
double getLength( void );
};
double Line::getLength(void)
{
return length ;
}
void Line::setLength( double len )
{
length = len;
}
int main( )
{
Line line;
line.setLength(6.0);
cout << "Length of line : " <<
line.getLength() <<endl;
line.length = 10.0;
cout << "Length of line : " << line.length
<<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Length of line : 6
Length of line : 10
The private members:
A private member variable or function cannot be accessed, or even viewed
from outside the class. Only the class and friend functions can access private members.
By default all the members of a class would be private, for example in the
following class width is a private member, which means until you label a member, it will
be assumed a private member:
23
class Box
{
double width;
public:
double length;
void setWidth( double wid );
double getWidth( void );
};
Practically, we define data in private section and related functions in public section so
that they can be called from outside of the class as shown in the following program.
Example:
class Box
{
public:
double length;
void setWidth( double wid );
double getWidth( void );
private:
double width;
};
double Box::getWidth(void)
{
return width ;
}
void Box::setWidth( double wid )
{
width = wid;
}
int main( )
{
Box box;
box.length = 10.0 cout << "Length of
box : " << box.length <<endl;
box.width = 10.0;
box.setWidth(10.0);
cout << "Width of box : " <<
box.getWidth() <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Length of box : 10
Width of box : 10
24
Example
class Box
{
protected:
double width;
};
class SmallBox:
{
public:
void setSmallWidth( double wid );
double getSmallWidth( void );
};
double SmallBox::getSmallWidth(void)
{
return width ;
}
void SmallBox::setSmallWidth( double wid )
{
width = wid;
}
int main( )
{
SmallBox box;
box.setSmallWidth(5.0);
cout << "Width of box : "<<
box.getSmallWidth() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Width of box : 5
25
Containers,
Algorithms
Iterators
Containers are objects that hold other objects. There are several different types of
containers. For example, the vector class defines a dynamic array, queue creates a
queue, and list provides a linear list.
Algorithms act on the contents of containers. They include capabilities for initializing,
sorting, searching, and transforming the contents of containers. Many algorithms
operate on a range of elements within a container.
Iterators are objects that act, more or less, like pointers. They give you the ability to
cycle through the contents of a container in much the same way that you would use a
pointer to cycle through an array.
In addition to containers, algorithms, and iterators, the STL relies upon several
other standard components for support. Each container has defined for it an allocator.
Allocators manage memory allocation for a container. The default allocator is an object
of class allocator, but you can define your own allocators if needed by specialized
applications.
The Container Classes
The containers defined by the STL and the headers necessary to use each container
are shown below,
26
Required
Container
Description
bitset
deque
list
map
A set of bits.
A double-ended queue.
A linear list.
Stores key/value pairs in which each key is
multimap
Header
<bitset>
<deque>
<list>
<map>
priority_queu
unique.
A priority queue.
<queue>
e
queue
set
stack
A queue.
A set in which each element is unique.
A stack.
<queue>
<set>
<stack>
vector
A dynamic array.
<vector>
Algorithms
Algorithms act on containers. Although each container provides support for its
own basic operations, the standard algorithms provide more extended or complex
actions. To have access to the STL algorithms, you must include <algorithm> in your
program.
Algorithm
adjacent_find
Purpose
Searches for adjacent matching elements within a sequence and
count
count_if
find
predicate.
Searches a range for a value and returns an iterator to the first
find_end
includes
lower_bound
sequence.
Finds the first point in the sequence that is not less than a specified
.
max
merge
value
Returns the maximum of two values.
Merges two ordered sequences, placing the result into a third
min
remove, emove_if,
sequence.
Returns the minimum of two values.
Removes elements from a specified range.
remove_copy,and
remove_copy_if
search
set_difference
set_intersection
ordered sets.
Produces a sequence that contains the intersection of the two
upper_bound
ordered sets.
Finds the last point in a sequence that is not greater than some
partial_sort
partial_sort_copy
value.
Sorts a range.
Sorts a range and then copies as many elements as will fit into a
resulting sequence.
Iterators
Iterators are similar to pointers.
Iterators
Random Access
Bidirectional
Forward
Input
Output
Access Allowed
Store and retrieve values. Elements may be accessed randomly.
Store and retrieve values. Forward and backward moving.
Store and retrieve values. Forward moving only.
Retrieve, but not store values. Forward moving only.
Store, but not retrieve values. Forward moving only.
In general, an iterator that has greater access capabilities can be used in place of
one that has lesser capabilities. For example, a forward iterator can be used in place of
an input iterator. Iterators are handled just like pointers. You can increment and
decrement them. You can apply the * operator to them. Iterators are declared using the
iterator type defined by the various containers.
The STL also supports reverse iterators. Reverse iterators are either
bidirectional or random-access iterators that move through a sequence in the reverse
28
direction. Thus, if a reverse iterator points to the end of a sequence, incrementing that
iterator will cause it to point to one element before the end.
Example:
int main()
vector<int> vec;
int i;
vector<int>::iterator v = vec.begin();
while( v != vec.end()) {
endl;
v++;
vec.push_back(i);
return 0;
When the above code is compiled and executed, it produces the following result:
vector size = 0
extended vector size = 5
value of vec [0] = 0
value of vec [1] = 1
value of vec [2] = 2
value of vec [3] = 3
value of vec [4] = 4
value of v = 0
value of v = 1
value of v = 2
value of v = 3
29
value of v = 4
5. Write a C++ program illustrating class declaration, definition and accessing
class members. (16m) [M/J2014]
Class
The classes are the most important feature of C++ that leads to Object Oriented
programming. Class is a user defined data type, which holds its own data members and
member functions, which can be accessed and used by creating instance of that class.
The variables inside class definition are called as data members and the functions are
called member functions.
Class of birds, all birds can fly and they all have wings and beaks. So here flying
is a behavior and wings and beaks are part of their characteristics. And there are many
different birds in this class with different names but they all posses this behavior and
characteristics.
Example, class Study
Objects
Class is mere a blueprint or a template. No storage is assigned when we define a
class. Objects are instances of class, which holds the data variables declared in class
and the member functions work on these class objects.
Example, Study obj;
Defining Class and Declaring Objects
When we define any class, we are not defining any data, we just define a
structure or a blueprint, as to what the object of that class type will contain and what
operations can be performed on that object.
Syntax of class definition,
class ClassName
Example:
class Student
Access specifier:
Data members;
public:
30
Member Functions()
int rollno;
string name;
}A,B;
};
Here A and B are the objects of class Student, declared with the class
definition. We can also declare objects separately, like we declare variable of primitive
data types. In this case the data type is the class name, and variable is the object.
int main()
{
Student A;
Student B;
}
Both A and B will have their own copies of data members.
Accessing Data Members of Class
Accessing a data member depends solely on the access control of that data
member. If its public, then the data member can be easily accessed using the direct
member access (.) operator with the object of that class. If, the data member is defined
as private or protected, then we cannot access the data variables directly. Access
specifiers in C++ class defines the access control rules. C++ has 3 new keywords
introduced, namely,
1 public
2 private
3 protected
Public
Public, means all the class members declared under public will be available to
everyone. The data members and member functions declared public can be accessed
31
by other classes too. Hence there are chances that they might change them. So the key
members must not be declared public.
class PublicAccess
{
public: // public access specifier
int x;
32
private :
int empno;
char name[20];
cout<<"Name
float basic,da,it,net_sal,gross_sal;
cout<<"basic :"<<basic<<"\n";
public :
cout<<"Net salary
:"<<name<<"\n";
:"<<net_sal<<"\n";
void read();
void cal();
void print();
void main()
};
employee e[10];
int i ,n;
clrscr();
cin>>empno;
cin>>n;
:";
for(i=0;i<n;i++)
cin>>name;
e[i].read();
employee :";
e[i].cal();
cin>>basic;
for(i=0;i<n;i++)
e[i].print();
getch();
da=basic*.52;
gross_sal=basic+da;
it=gross_sal*.30;
net_sal=gross_sal-it;
33
Output:
Enter the no. of employee :2
Enter the emp no. :1
Enter the name of the employee :alok
Enter the basic salary of the employee :6000
Enter the emp no. :2
Enter the name of the employee :pravin
Enter the basic salary of the employee :7000
Emp No. :1
Name
:alok
basic :6000
Net salary
:6384
Emp No. :2
Name
:pravin
basic :7000
Net salary
:7448
}
void books :: putdata ()
{
cout<<"Title:"<<title<< "\n";
cout<<"Price:"<<price<< "\n;
const int size=3 ;
int main ()
{
books book[size] ;
for(int i=0;i<size;i++)
{
cout<<"Enter details o book "<<(i+1)<<"\n";
35
book[i].getdata();
}
for(int i=0;i<size;i++)
{
cout<<"\nBook "<<(i+l)<<"\n";
book[i].putdata() ;
}
return 0;
}
Title: DBMS
Price: 455
Book 3
Title: Java
Price: 255
In this example, an array book of the type class books and size three is declared. This
implies that book is an array of three objects of the class books. Note that every object
in the array book can access public members of the class in the same way as any other
object, that is, by using the dot operator. For example, the statement book [i] . getdata ()
invokes the getdata () function for the ith element of array book.
When an array of objects is declared, the memory is allocated in the same way as to
multidimensional arrays. For example, for the array book, a separate copy of title and
price is created for each member book[0], book[l] and book[2]. However, member
functions are stored at a different place in memory and shared among all the array
members. For instance, the memory space is allocated to the array of objects book of
the class books.
8. What is operator overloading in c++ ? List out the rules to overload a binary
operator [M/J2016][7]
Operators overloading in C++
We can redefine or overload most of the built-in operators available in C++. Thus a
programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names the keyword operator followed
by the symbol for the operator being defined. Like any other function, an overloaded
operator has a return type and a parameter list.
Box operator+(const Box&);
declares the addition operator that can be used to add two Box objects and returns final
Box object. Most overloaded operators may be defined as ordinary non-member
functions or as class member functions. In case we define above function as nonmember function of a class then we would have to pass two arguments for each
operand as follows:
Box operator+(const Box&, const Box&);
37
which would not be accepted otherwise, and we can even modify the effect of operators
that they already admit. Here is a list of all the operators that can be overloaded:
<
>
+= -= *= /= << >>
&
Here we have an example that includes the operator +. We are going to sum the
bidimensional vectors a(3,1) and b(1,2). The addition of two bidimensional vectors is an
operation as simple as adding the two x coordinates to obtain the resulting x coordinate
and adding the two y coordinates to obtain the resulting y. In this case the result will be
(3+1,1+2) = (4,3).
class CVector {
public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
39
};
int main () {
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b;
cout << c.x << "," << c.y;
return 0;
}
4,3
40
If you are baffled seeing CVector so many times, consider that some of them make
reference to the class name CVector and others are functions with that name. Do not
confuse them:
The function operator+ of class CVector is the one that is in charge of overloading the
arithmetic operator +. This one can be called by any of these two ways:
c = a + b;
c = a.operator+ (b);
Notice also that we have incuded the empty constructor (without parameters) and we
have defined it with a no-op block of instructions:
CVector () { };
so none of the default constructors will exist in CVector if we do not explicitly declare
one as we have done. Otherwise the declaration
CVector c;
41
Anyway, I have to warn that a no-op block is not a recommended implementation for a
constructor, since it does not fulfill the minimum functionality that a constructor should
have, which is the initialization of all the variables in the class. In our case this
constructor leaves variables x and y undefined. Therefore, a more advisable declaration
would have been something similar to this:
CVector ()
{
x=0;
y=0;
};
It is initialized to zero when the first object of its class is created. No other
initialization is permitted.
Only one copy of that member is created for the entire class and is shared by all
the objects of that class, no matter how many objects are created.
It is visible only within the class, but its lifetime is the entire program.
the this pointer.
42
Note the use of the scope resolution operator. A static member of a global class must be
explicitly declared and defined in file scope
Example:
class item
{
static int count;
public:
void get()
{
count++;
}
void put()
{
cout<<"Count"<<count<<"\n";
}
};
int item::count;
//definition of the static
data member
void main()
{
item ob,ob1,ob2;
clrscr();
ob.get();
ob1.get();
ob2.put();
ob2.get();
ob.put();
ob1.put();
ob2.put();
getch();
}
Note that the type and scope of each static member variable must be defined outside
the class definition. This is necessary because the static data members are stored
separately.
Static member functions [A/M2011]
Like static variable, we can also have static member functions. A member
function that is declared static has the property that a static function can have access to
only other static members (functions or variables) declared in the same class.
It has some restrictions:
They do not possess this pointer because they are not member functions.
They cannot access other data member of the class because doing so it will
implicitly call the this pointer.
A static member function can be called using the class name instead of its objects as
follows:
43
class-name :: function-name();
Example:
class item
{
static int count;
public:
void get()
{
count++;
}
static void put()
{
cout<<"Count"<<count<<"\n";
}
};
int item::count;
//definition of the static data
member
void main()
{
item ob,ob1,ob2;
clrscr();
ob.get();
ob1.get();
item::put(); // definition of the static member
function
ob2.get();
item::put();
getch();
}
b=10;
int b;
int c=ob.a+b; //
public:
cout<<c;
class inner
};
public:
void main()
int a;
{
44
void ass()
clrscr();
outer ob1;
a=10;
outer::inner ob;
};
class
void add(inner ob) //function definition in ob1.add(ob); // call the function defined in
outer class with inner class object as outer class
argument
getch();
}
In this example, we define the class inner inside the class outer in public section. The
statement outer ob1 will create an object for the outer class. Outer::inner ob will create
an object for the class inner.
9. Explain about member functions in detail.
Member Functions
C++ allows functions to be members. C allows only data members. The function
declaration is included in the structure declaration. The idea is that the functionality
required by the structure or class should often be directly included in the class or struct
declaration. Such functions are called class methods. This term method, meaning
member function, comes from object-oriented programming methodology.
Defining member functions
Member functions can be defined in two places;
Syntax:
Class class_name
{
Data members;
class,
Syntax:
45
return-type Function_name(arguments)
{
return-type class-name::functionname(arguments)
Example:
class Sum
Example:
class Sum
private:
{
int a,b,c;
private:
public:
int a,b,c;
public:
class
};
};
a=10;
b=20;
the class
c=a+b;
cout<<Sum is<<c;
a=10;
b=20;
c=a+b;
cout<<Sum is<<c;
}
The membership label class-name :: tells the compiler that the function
function-name belongs to the class class-name. that is the scope of the function is
restricted to the class-name specified in the header line. The symbol :: is called the
scope resolution operator. Since the functions do not return any value, their return type
is void.
Several different classes can use the same function name. The memebership
label will resolve their scope.
Member functions can access the private data of the class. A non member
function cannot do so.
// global variable
int main() {
char c = 'b'; //local variable
cout << "Local variable: " << c << "\n";
cout << "Global variable: " << ::c << "\n"; //using scope resolution operator
return 0;
}
Output:
Local variable: b
Global variable: a
Scope resolution operator in class
class programming
{
public:
void output(); //function declaration
};
// function definition outside the class
void programming::output() {
cout << "Function defined outside the class.\n";
}
47
int main() {
programming x;
x.output();
return 0;
}
Output:
Function defined outside the class.
10. Write a program to perform the following using Function Overloading [N/D2012]
(i)To read a set of integers
(ii)To read a set of floating point numbers
(iii) To read a set of double numbers and Find out the Average.
void average(int,int);
void average(float,float);
void add(double,double);
class Sum
{
int a,b,c;
float d,e,f,avg;
double g,h,i;
public:
void average()
{
a=10;
b=20;
c=a+b;
avg=c/2;
cout<< the average of integer nos is <<avg<<"\n";
}
void average(float x,float y)
48
{
d=x;
e=y;
f=d+e;
avg=f/2;
cout<< the average of float nos is <<avg<<"\n";
}
void average(double p,double q)
{
g=p;
h=q;
i=g+q;
avg=i/2;
cout<< the average of double nos is <<avg<<"\n";
}
};
void main()
{
Sum ob;
clrscr();
ob.average(30,20);
ob.average(20.3f,20.2f);
ob.average(10.5d,11.5d);
getch();
}
49