C++
Author : Aarav Patel
OOPs Programming Language
Object
-------
Any entity that has state and behavior is known as an object.
For example: chair, pen, table, keyboard, bike etc.
Class
------
Collection of objects is called class.
Inheritance
------------
When one object acquires all the properties and behaviour of parent
object.
Polymorphism
-------------
When one task is performed by different ways.
For example: to convince the customer differently, to draw something e.g. shape or
rectangle etc.
Abstraction
------------
Hiding internal details and showing functionality.
For example: phone call, we don't know the internal processing.
Encapsulation
--------------
Binding (or wrapping) code and data together into a single unit is known as
encapsulation.
For example: capsule, it is wrapped with different medicines.
Visibilities
------------
Public: When the member is declared as public, it is
accessible to all the functions of the program.
Private: When the member is declared as private, it is
accessible within the class only.
Protected: When the member is declared as protected,
it is accessible within its own class as well as the
class immediately derived from it.
Note :
For the tasks visit the following links
Constructor
It is a special method that is invoked automatically at the time of object creation.
OOPs Programming Language Continue
Class
--------
It is a user-defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class.
A class is like a blueprint for an object.
Example : Consider the Class of Cars. There may be many cars with different names and
brands but all of them will share some common properties like all of them will have
4 wheels, Speed Limit, Mileage range, etc. So here, the Car is the class, and wheels,
speed limits, and mileage are their properties.
Some other info about class are :
Data members are the data variables and member functions are the functions used to manipulate these
variables together these data members and member functions define the properties and behavior of the
objects in a Class.
Object
An Object is an identifiable entity with some characteristics and behavior. An Object is an
instance of a Class.
When a class is defined, no memory is allocated but when it is
instantiated (i.e. an
object is created) memory is allocated.
Encapsulation
Encapsulation is defined as binding together the data and the functions that manipulate
them.
Consider a real-life example of encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section, etc. The finance section handles all the financial transactions
and keeps records of all the data related to finance. Similarly, the sales section handles all the sales-related
activities and keeps records of all the sales.
Abstraction
Abstraction means displaying only essential information and hiding the details.
Data abstraction refers to providing only essential information about the data to the outside
world, hiding the background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerator will increase the speed of the car or applying brakes will stop the car but he does
not know how on pressing the accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of an accelerator, brakes, etc. in
the car.
Abstraction using Classes: We can implement Abstraction in C++ using classes. The class helps
us to group data members and member functions using available access specifiers. A Class can
decide which data member will be visible to the outside world and which is not.
• Abstraction in Header files: One more type of abstraction in C++ can be header files. For
example, consider the pow() method present in “math.h” header file. Whenever we need to
calculate the power of a number, we simply call the function pow() present in the “math.h”
header file and pass the numbers as arguments without knowing the underlying algorithm
according to which the function is actually calculating the power of numbers.
Polymorphism
In simple words, we can define polymorphism as the ability of a message to be displayed in
more than one form.
Operator Overloading: The process of making an operator exhibit different behaviors in
different instances is known as operator overloading.
Function Overloading: Function overloading is using a single function name to perform
different types of tasks. Polymorphism is extensively used in implementing inheritance.
Inheritance
The capability of a class to derive properties and characteristics from
another class is called.
• 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 a sub-class
is called Base Class or Superclass.
•Reusability: Inheritance supports the concept of “reusability”, i.e.
when we want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
Dynamic Binding
In dynamic binding, the code to be executed in response to the function call is decided at
runtime.
Because dynamic binding is flexible, it avoids the drawbacks of static binding, which
connected the function call and definition at build time.
Message Passing
Objects communicate with one another by sending and receiving information. A message
for an object is a request for the execution of a procedure and therefore will invoke a
function in the receiving object that generates the desired results. Message passing
involves specifying the name of the object, the name of the function, and the information
to be sent.
Virtual function
• A C++ virtual function is a member function in the base class that you
redefine in a derived class. It is declared using the virtual keyword.
•It is used to tell the compiler to perform dynamic linkage or late binding on
the function.
•There is a necessity to use the single pointer to refer to all the objects of
the different classes. So, we create the pointer to the base class that refers
to all the derived objects. But, when base class pointer contains the address
of the derived class object, always executes the base class function. This
issue can only be resolved by using the 'virtual' function.
•A 'virtual' is a keyword preceding the normal declaration of a function.
•When the function is made virtual, C++ determines which function is to be
invoked at the runtime based on the type of the object pointed by the base
class pointer.
Exception Handling
Exception Handling in C++ is a process to handle runtime errors. We perform exception
handling so the normal flow of the application can be maintained even after runtime
errors.
In C++, exception is an event or object which is thrown at runtime. All exceptions are
derived from std::exception class. It is a runtime error which can be handled. If we don’t
handle the exception, it prints exception message and terminates the program.
It’s Advantages
It maintains the normal flow of the application. In such case, rest of the code is
executed even after exception.
Exception Classes
It maintains the normal flow of the application. In such case, rest of the code is
executed even after exception.
Exception Description
std::exception It is an exception and parent class of all standard C++ exceptions.
std::logic_failure It is an exception that can be detected by reading a code.
std::runtime_error It is an exception that cannot be detected by reading a code.
std::bad_exception It is used to handle the unexpected exceptions in a C++ program.
std::bad_cast This exception is generally be thrown by dynamic_cast.
std::bad_typeid This exception is generally be thrown by typeid.
std::bad_alloc This exception is generally be thrown by new.
In C++, we use 3 keywords to perform exception handling:
try
catch, and
throw
C++ Templates
A C++ template is a powerful feature added to C++. It allows you to define the generic
classes and generic functions and thus provides support for generic programming. Generic
programming is a technique where generic types are used as parameters in algorithms so
that they can work for a variety of data types.
Templates can be represented in two ways:
Function templates
Class templates
1) Function Templates
We can define a template for a function. For example, if we have an add() function, we can
create versions of the add function for adding the int, float or double type values.
2) Class Template
We can define a template for a class. For example, a class template can be created for the
array class that can accept the array of various types such as int array, float array or double
array.
Function Template
Generic functions use the concept of a function template. Generic functions define a set of
operations that can be applied to the various types of data.
The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
For example, Quick sorting algorithm is implemented using a generic function, it can be
implemented to an array of integers or array of floats.
A Generic function is created by using the keyword template. The template defines what
function will do.
Syntax :
template < class Ttype> ret_type func_name(parameter_list)
{
// body of function.
}
Where Ttype: It is a placeholder name for a data type used by the function. It is
used within the function definition. It is only a placeholder that the compiler will
automatically replace this placeholder with the actual data type.
Class: A class keyword is used to specify a generic type in a template declaration.
Function Templates with Multiple Parameters
We can use more than one generic type in the template function by using
the comma to separate the list.
Syntax
template<class T1, class T2,.....>
return_type function_name (arguments of type T1, T2....)
{
// body of function.
}
Overloading a Function Template
We can overload the generic function means that the overloaded template functions can
differ in the parameter list.
Restrictions of Generic Functions
Generic functions perform the same operation for all the versions of a function except the
data type differs. Let's see a simple example of an overloaded function which cannot be
replaced by the generic function as both the functions have different functionalities.
We cannot overload the generic functions as both the functions have different functionalities.
CLASS TEMPLATE
Class Template can also be defined similarly to the Function Template. When a class uses the
concept of Template, then the class is known as generic class.
Syntax
template<class Ttype>
class class_name
{
.
.
}
Ttype is a placeholder name which will be determined when the class is instantiated. We can
define more than one generic data type using a comma-separated list. The Ttype can be used
inside the class body.
CLASS TEMPLATE WITH MULTIPLE PARAMETERS
We can use more than one generic data type in a class template, and each generic data type
is separated by the comma.
Syntax
template<class T1, class T2, ......>
class class_name
{
// Body of the class.
}
Non-type Template Arguments
The template can contain multiple arguments, and we can also use the non-type arguments
In addition to the type T argument, we can also use other types of arguments such as
strings, function names, constant expression and built-in types.
Points to Remember
C++ supports a powerful feature known as a template to implement the concept of
generic programming.
A template allows us to create a family of classes or family of functions to handle different
data types.
Template classes and functions eliminate the code duplication of different data types and
thus makes the development easier and faster.
Multiple parameters can be used in both class and function template.
Template functions can also be overloaded.
We can also use non-type arguments such as built-in or derived data types as template
arguments.