C++ Inline and Friend Functions Explained
C++ Inline and Friend Functions Explained
Object-Oriented Programming
Concepts
7.1 Inline function
• We say that using functions in a program is to save some memory space because all the
calls to the functions cause the same code to be executed. However, every time a function
is called, it takes a lot of extra time in executing a series of instructions.
• Since the tasks such as jumping to the function, saving registers, pushing arguments into
the stack and returning to the calling function are carried out when a function is called.
When a function is small, considerable amount of time is spent in such overheads.
• C++ has a solution for this problem. To eliminate the cost of calls to small functions, C++
proposed a new feature called INLINE function.
• When a function is defined as inline, compiler copies its body where the function call is
made, instead of transferring control to that function. So, it is used only for small functions.
• A function is made inline by using a keyword “inline” before the function definition.
• It should be noted that, the inline keyword is just a request to the compiler to make the
function inline function, not a command.
• The compiler may not always accept this request. It may ignore the request if the function
is too long or complicated and compile the function as normal function. Some situations
where inline expansion may not work are:
✓ for functions having loop, switch or go-to statements
✓ for recursive functions
✓ functions with static variables
✓ for functions not returning values, if a return statement exists
• Advantage: Increase execution speed.
• Disadvantages: More memory required because of copying.
Example 1:
#include<conio.h>
#include<iostream>
using namespace std;
//While declartion no need for keyword inline
int Findcube(int x);
int main()
{
cout<<Findcube(3);
getch();
return 0;
}
inline int Findcube(int x)
{
return x*x*x;
}
Example 2:
#include<iostream.h>
inline float lbtokg(float lbs)
{
return (0.453 * lbs);
}
int main()
{
float lbs, kgs;
cout<<”Enter weight in lbs:”;
cin>>lbs;
kgs=lbtokg(lbs);
cout<<”Weight in kg is ”<<kgs;
return (0);
}
Example 3:
WAP to display hello world by using class and inline member function.
#include<iostream>
using namespace std;
class Demo
{
public:
inline void display();
};
int main()
{
Demo d;
[Link]();
}
inline void Demo:: display() //Defining outside the class
{
cout<<"hello world";
}
int main( )
{
cout<<"The output is: "<<add(10,20)<<endl;
cout<<"The output is: "<<add(10.70,20.10)<<endl;
return 0;
}
int add(int a, int b)
{
return(a+b);
}
double add(double a, double b)
{
return(a+b);
}
• Example 2:
#include <iostream>
using namespace std;
int area(int) ; // function area with int return type
double area(double, int) ; // function area with double return type
long area(long, int, int) ; // function area with long return type
int main( )
{
cout<<area(10)<<endl;
cout<<area(2.5,8)<<endl;
cout<<area(100,75,15)<<endl;
return 0 ;
}
int area(int s) // square
{
return(s*s) ;
}
double area(double r, int h) // Surface area of cylinder ;
{
return(2*3.14*r*h) ;
}
long area(long l, int b, int h) //area of parallelopiped
{
return(2*(l*b+b*h+l*h)) ;
}
7.4 Inheritance
• Inheritance is the most powerful feature of object-oriented programming.
• Inheritance is the process of creating new classes, called derived classes, from existing
classes or base classes. The class inherits all the capabilities of the base class but can add
refinements of its own.
• When new class is created based on some other class using inheritance, the newly created
class is called the derived class or sub-class, while the class on which it is based is called
base class or superclass.
✓ Sub-Class: The class that inherits properties from another class is called Sub class
or Derived Class.
✓ Super-Class: The class whose properties are inherited by sub class is called Base
Class or Super class.
• The derived class inherits some or all the traits from base class. The base class is unchanged
by this. Most important advantage of inheritance is re-usability. Once a base class is written
and debugged, it need not be touched again and we can use this class for deriving another
class if we need. Reusing existing code saves time and money. By re-usability a
programmer can use a class created by another person or company and without modifying
it derive other class from it.
• Syntax:
class subclass_name : access_mode base_class_name
{
//body of subclass
};
Purpose of Inheritance
• Code Reusability
• Method Overriding (Hence, Runtime Polymorphism.)
• Use of Virtual Keyword
Advantages of Inheritance
• Inheritance promotes reusability. When a class inherits or derives another class, it can
access all the functionality of inherited class.
• Reusability enhanced reliability. The base class code will be already tested and debugged.
• As the existing code is reused, it leads to less development and maintenance costs.
• Inheritance makes the sub classes follow a standard interface.
• Inheritance helps to reduce code redundancy and supports code extensibility.
• Inheritance facilitates creation of class libraries
Disadvantages of Inheritance
• Inherited functions work slower than normal function as there is indirection.
• Improper use of inheritance may lead to wrong solutions.
• Often, data members in the base class are left unused which may lead to memory wastage.
• Inheritance increases the coupling between base class and derived class. A change in base
class will affect all the child classes
Example of Inheritance
// C++ program to demonstrate implementation of Inheritance
#include <iostream>
using namespace std;
//Base class
class Parent
{
public:
int id_p=9;
};
//main function
int main ()
{
Child obj1;
cout << "Child id is " << obj1.id_c << endl;
cout << "Parent id is " << obj1.id_p << endl;
return 0;
}
// C++ Implementation to show that a derived class doesn’t inherit access to private data
members. However, it does inherit a full parent object
class A
{
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};
class D : private A // 'private' is default for classes
{
// x is private
// y is private
// z is not accessible from D
};
Types of Inheritance
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
1. Single Inheritance
• In single inheritance, a sub-class is derived from only one super class.
• It inherits the properties and behavior of a single-parent class. Sometimes, it is also known
as simple inheritance.
• Syntax:
class A // base class
{
private:
{
…. // body part
…
}
public:
{
…..// body part
…..
}
};
class B : public A // derived class B
{
……
…..
};
• Example 1:
#include <iostream>
using namespace std;
class Vehicle {
public:
Vehicle() {
cout << "This is a Vehicle" << endl;
}
};
class Car : public Vehicle {
public:
Car() {
cout << "This Vehicle is Car" << endl;
}
};
int main() {
Car obj;
return 0;
}
• Example 2: A class Room consists of two fields length and breadth and method int area()
to find the area of room. A new class BedRoom is derived from class Room and consist of
additional field height and two methods setData(int,int,int) to set the value for three fields
and int volume() to find the volume. Now write the C++ program to input the length
,breadth and height and find the area and volume.
#include<iostream>
using namespace std;
class Room
{
protected:
float length, breadth;
public:
int area()
{
return(length*breadth);
}
};
class BedRoom : public Room
{
private:
float height;
public:
void setData(int l, int b, int h)
{
length=l;
breadth=b;
height=h;
}
int volume()
{
return(length * breadth * height);
}
};
int main()
{
BedRoom b;
[Link](3,4,5);
cout<<"Area of bedroom= "<<[Link]()<<endl;
cout<<"Volume of bedroom="<<[Link]();
}
2. Multiple Inheritance
• In Multiple inheritance, one class can have more than one superclass and inherit features
from all parent classes.
• Syntax:
class A
{
…….
……
};
class B
{
…….
……
};
class C : public A, public B, public …n
{
…….
……
};
• Here two base classes A and B have been created and a derived class C is created from
both base classes.
• Example 1:
#include <iostream>
using namespace std;
class LandVehicle
{
public:
void landInfo()
{
cout << "This is a LandVehicle" << endl;
}
};
class WaterVehicle
{
public:
void waterInfo()
{
cout << "This is a WaterVehicle" << endl;
}
};
int main()
{
AmphibiousVehicle obj;
[Link]();
[Link]();
return 0;
}
• Example 2: Create two classes class1 and class2 each having data member for storing a
number, a method to initialize it. Create a new class class3 that is derived from both class
class1 and class2 and consisting of a method that displays the sum of two numbers from
class1 and class2.
#include<iostream>
using namespace std;
class class1
{
protected:
int n;
public:
void getn(int p)
{
n=p;
}
};
class class2
{
protected:
int m;
public:
void getm(int q)
{
m=q;
}
};
//Derived class
class class3: public class1, public class2
{
public:
void displaytotal()
{
int tot;
tot=n+m;
cout<<"Sum ="<<tot;
}
};
int main()
{
class3 a;
[Link](4);
[Link](5);
[Link]();
}
3. Multilevel Inheritance
• Multilevel inheritance in C++ means a class is derived from another derived class, forming
a chain of inheritance.
• Syntax:
class A
{
//member of A
}
class B :public/private/protected A
{
//own member of B
}
class C :public/private/protected B
{
//own member of C
}
• In above case, class B is derived from Class A while class C is derived from derived class
B. So, the class A serves as base class for B and B serves as base class for C therefore B is
also called as intermediate class because it provides a link between class A and C.
• Example 1:
#include <iostream>
using namespace std;
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
int main()
{
Car obj;
return 0;
}
• Example 2: A class Student consists of field roll, a method to assigns roll number. A new
class Test is derived from class Student and consists of two new fields sub1 and sub2, a
method to initialize these fields with obtained mark. Again, a new class Result is derived
from Test and consists of a field total and a method to display entire details along with total
obtained marks. WAP to input roll number, marks in two different subject and display total.
#include<iostream>
using namespace std;
class Student
{
protected:
int roll;
public:
void setroll(int r)
{
roll=r;
}
};
class Test: public Student
{
protected:
float sub1, sub2;
public:
void setmark(float m1, float m2)
{
sub1=m1;
sub2=m2;
}
};
class Result : public Test
{
private:
float total;
public:
void display()
{
total=sub1+sub2;
cout<<"Roll number= "<<roll<<endl;
cout<<"Mark in first subject= "<<sub1<<endl;
cout<<"Mark in second subject= "<<sub2<<endl;
cout<<"Total= "<<total;
}
};
int main()
{
int r;
float s1,s2;
cout<<"Enter roll number"<<endl;
cin>>r;
cout<<"Enter marks in two subject"<<endl;
cin>>s1>>s2;
Result res;
[Link](r);
[Link](s1,s2);
[Link]();
}
Function Overriding
• In C++, a base class member can be overridden by defining a derived class member with
the same name as that of the base class member.
• Function overriding is an object-oriented concept in which a derived (child) class provides
its own implementation of a function that already exists in the base (parent) class, using
the same function name, same parameters, and same return type.
• It supports runtime polymorphism.
• Example:
#include<iostream>
using namespace std;
class Abase //Base class
{
public:
void show()
{
cout<<”I am Base class.”<<endl;
}
};
class Bderived : public Abase //Derived class
{
public:
void show()
{
cout<<”I am Derived class”<<endl;
}
};
int main()
{
Bderived Bobj;
[Link]();
What is template?
• Templates are the foundation of generic programming, which involves writing code in a
way that is independent of any type.
• A template is a blueprint or formula for creating a generic class or a function.
• A template is one of the recently added feature in C++. It supports the generic data types
and generic programming.
• Generic programming is an approach where generic data types are used as parameters in
algorithms so that they can work for a variety of suitable data types.
Example:
✓ A class template for an array class would enable us to create arrays of various data
types such as int, array and float array.
✓ A function template say mul() can be used for multiplying int, float and double type
values.
• A Template can be considered as Macro. When an object of specific type is defined for
actual use, the template definition for that class is substituted with the required data type.
• Since a template is defined with a parameter that would be replaced by a specified data
type at the time of actual use of the class or function, the template is also called as
parametrized class or functions.
Features of Template
• Templates are easier to write. We can create only one generic version of our class or
function instead of manually creating specializations.
• Templates are easier to understand, since they provide a straightforward way of abstracting
type
• information.
• Templates are type safe. Because the types that templates act upon are known at compile
time, the compiler can perform type checking before errors occur.
What is template function?
• In C++, function overloading allows to define multiple functions with the same names but
with different arguments.
• In a situation, where we need to define functions with the same body but of different data
type, we can use function overloading. But while overloading a function, different
data types will need different functions, and hence the function needs to be rewritten
several times for each data type. This is time consuming and space consuming. So, C++
introduced the new concept of function template.
• Function template are special functions that can operate with generic types. It is the
function which is written just for once, and have it worked for many different data types.
• The key innovation in function templates is to represent the data type used by the function
not as a specific type such as int, float, etc., but as a name that can stand for any type.
• The general format for function template is given below:
template<class T> or template<typename T>
returnType of type Tfunction_name (argument of type T)
{
//body of function with type T whenever appropriate
}
Note: Main function can’t be declared as template
• The template keyword signals the compiler that we’re about to define a function template.
The keyword class, with angle brackets, acts as the type. We can define our own data type
using classes, so there’s no distinction between types and classes. The variable following
keyword class (‘T’ in above syntax) is called the template argument.
Example:
1. #include <iostream>
using namespace std;
template <class T1> or template <typename T1>
// In templates, the keyword class is used to declare a generic data type. It does not
mean a C++ class; it simply tells the compiler that T represents a type.
T1 sum (T1 a, T1 b)
{
return (a+b);
}
int main()
{
cout << sum(10, 20) << endl;
cout << sum(11.5, 13.1) << endl;
return 0;
}
Output:
30
24
In the above example, sum() is a template function. It takes two arguments of T1 type and
returns a T1 type data equal to the sum of two arguments. Defining a function as a template
doesn’t generate code for different types; it is just a message to the compiler that the
function can be called with different data types. Thus, in main(), when sum(10, 20) is
called, the template generates a function by substituting the template argument (T1) with
int. This is called instantiating the function template, and each instantiated version of the
function is called a template function.
When sum(11.5, 13.1) is invoked, instantiation of the template by float takes place and
another template function of float type is created.
Note: The compiler generates only one version of the function for each data type.
2. WAP to declare template function that can be used to find the area of rectangle.
#include<iostream>
using namespace std;
template<class t>
t area(t len, t bre)
{
return(len*bre);
}
int main()
{
int l1=6, b1=4;
cout<<"Area= "<<area(l1, b1)<<endl;
float l2=2.5, b2=2.0;
cout<<"Area= "<<area(l2, b2);
}
3. Function Template to Find Maximum of Two Numbers
#include <iostream>
using namespace std;
int main()
{
cout << maximum(10, 20) << endl;
cout << maximum(12.5, 9.8) << endl;
cout << maximum('A', 'Z') << endl;
return 0;
}
4. WAP to declare a function template that can be used to swap two values of a given type of data.
//using concept of pointer
#include <iostream>
using namespace std;
template<class T >
void swap( T *fn, T *sn )
{
T tmp;
tmp=*fn;
*fn=*sn;
*sn=tmp;
}
int main()
{
int m=5,n=6;
cout<<"Before swapping"<<endl;
cout<<"M= "<<m<<endl<<"N= "<<n<<endl;
swap(&m,&n);
cout<<"After swapping"<<endl;
cout<<"M= "<<m<<endl<<"N= "<<n<<endl;
}
Exception
• An exception is a run-time error. Proper handling of exceptions is an important
programming issue. This is because exceptions can and do happen in practice and programs
are generally expected to behave gracefully in face of such exceptions.
• Unless an exception is properly handled, it is likely to result in abnormal program
termination and potential loss of work. For example, an undetected division by zero or
dereferencing of an invalid pointer will almost certainly terminate the program abruptly.
Types
i. Synchronous: Exception that are caused by events that can be control of program is
called synchronous exception. Example, array index out or range exception.
ii. Asynchronous: Exception that are caused by events beyond the control of program is
called synchronous exception. Example, Exception generated by hardware
malfunction.
try
{
res=divide(nu,de);
cout<<"Result= "<<res;
}
catch(int i) //catches the int type exception
{
cout<<"Divide by zero exception occurred: de= "<<i;
}
}
int divide(int fn, int sn)
{
if(sn==0)
{
throw(sn);
}
else
{
return(fn/sn);
}
}
• Example 2:
Other Examples:
1.
2.
3. WAP to input two numbers and divide first number by second. The result must be stored in the
index entered by user.
4.