0% found this document useful (0 votes)
135 views57 pages

Programming Paradigms Explained

Uploaded by

ramesh88074
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
135 views57 pages

Programming Paradigms Explained

Uploaded by

ramesh88074
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT 1

EVALUATION OF PROGRAMMING PARADIGM:

Paradigm can also be termed as method to solve some problem or do some task.
Programming paradigm is an approach to solve problem using some programming language or
also we can say it is a method to solve a problem using tools and techniques that are available
to us following some approach. There are lots for programming language that are known but
all of them need to follow some strategy when they are implemented and this
methodology/strategy is paradigms. Apart from varieties of programming language there are
lots of paradigms to fulfill each and every demand.

IMAGE 1: Programming Paradigms


DIFFERENCE BETWEEN PROCEDURAL ORIENTED PROGRAMMING
OBJECT-ORIENTED PROGRAMMING:

PROCEDURAL ORIENTED OBJECT-ORIENTED


PROGRAMMING PROGRAMMING
In procedural programming, the program is In object-oriented programming, the program
divided into small parts called functions. is divided into small parts called objects.
Procedural programming follows a top-down Object-oriented programming follows
approach. a bottom-up approach.
There is no access specifier in procedural Object-oriented programming has access
programming. specifiers like private, public, protected, etc.
Adding new data and functions is not easy. Adding new data and function is easy.
Procedural programming does not have any Object-oriented programming provides data
proper way of hiding data so it is less secure. hiding so it is more secure.
In procedural programming, overloading is Overloading is possible in object-oriented
not possible. programming.
In procedural programming, there is no In object-oriented programming, the concept
concept of data hiding and inheritance. of data hiding and inheritance is used.
In procedural programming, the function is In object-oriented programming, data is more
more important than the data. important than function.
Procedural programming is based on Object-oriented programming is based on
the unreal world. the real world.
Procedural programming is used for designing Object-oriented programming is used for
medium-sized programs. designing large and complex programs.
Procedural programming uses the concept of Object-oriented programming uses the
procedure abstraction. concept of data abstraction.
Code reusability absent in procedural Code reusability present in object-oriented
programming, programming.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
ELEMENTS OF OBJECT ORIENTED PROGRAMMING:

The prime purpose of C++ programming was to add object orientation to the C
programming language, which it itself one of the most powerful programming languages.

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. 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.

CLASS:

The building block of C++ that leads to Object-Oriented programming is a 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. Data members are the data variables
and member functions are the functions used to manipulate these variables and together these
data members and member functions define the properties and behaviour of the objects in a
Class. A class is like a blueprint for an object.

For Example: Consider the Class of Cars. There may be many cars with different
names and brand but all of them will share some common properties like all of them will have
4 wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits,
mileage are their properties.

DATA ABSTRACTION AND ENCAPSULATION:

Data abstraction is one of the most essential and important features of object-oriented
programming in C++. 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.
Encapsulation is defined as wrapping up of data and information under a single unit. In
Object-Oriented Programming, Encapsulation is defined as binding together the data and the
functions that manipulate them.

INHERITANCE:

Inheritance is the process by which objects of one class acquire the properties of object
of another class. It supports the concept of hierarchical classification.
 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.
 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.

DIFFERENCE BETWEEN BASE CLASS AND DERIVED CLASS:

[Link]. BASE CLASS DERIVED CLASS


1. A class from which properties are A class from which is inherited from the base
inherited. class.
2. It is also known as parent class or
superclass. It is also known as child class subclass.
3. It cannot inherit properties and It can inherit properties and methods of Base
methods of Derived Class. Class.
Syntax:
Syntax: Class derived_classname : access_mode
Class base_classname base_class_name
{ {
4. … …
}. }.
POLYMORPHISM:

The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.

A person at the same time can have different characteristic. Like a man at the same time
is a father, a husband, an employee. The same person poses different behaviour in different
situations. This is called polymorphism.

An operation may exhibit different behaviours in different instances. The behaviour


depends upon the types of data used in the operation.

C++ supports operator overloading and function overloading. Polymorphism is


extensively used in implementing inheritance.

 Operator Overloading: The process of making an operator to exhibit different behaviours


in different instances is known as operator overloading.
 Function Overloading: Function overloading is using a single function name to perform
different types of tasks.

FRIEND CLASS:

A friend class can access private and protected members of other class in which it is
declared as friend. It is sometimes useful to allow a particular class to access private members
of other class.
For example, a LinkedList class may be allowed to access private members of Node.
A friend class can access both private and protected members of the class in which it has been
declared as friend.

FRIEND FUNCTION:
Like friend class, a friend function can be given a special grant to access private and
protected members. A friend function can be:

a) A member of another class


b) A global function
 A friend function is a special function in C++ which in-spite of not being member function
of a class has privilege to access private and protected data of a class.
 A friend function is a non member function or ordinary function of a class, which is
declared as a friend using the keyword “friend” inside the class. By declaring a function as
a friend, all the access permissions are given to the function.
 The keyword “friend” is placed only in the function declaration of the friend function and
not in the function definition.
 When friend function is called neither name of object nor dot operator is used. However it
may accept the object as argument whose value it want to access.
 Friend function can be declared in any section of the class i.e. public or private or
protected.
Syntax :

class <class_name>

friend <return_type> <function_name>(argument/s); };

Following are some important points about friend functions and classes:
1) Friends should be used only for limited purpose. Too many functions or external classes are
declared as friends of a class with protected or private data, it lessens the value of
encapsulation of separate classes in object-oriented programming.
2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A
automatically.
3) Friendship is not inherited.
4) The concept of friends is not there in Java.

MERITS:
 A friend function is able to access members without the need of inheriting the class.
 Friend function acts as a bridge between two classes by accessing their private data.
 It can be used to increase the versatility of overloaded operator.
 It can be declared either in the public or private or protected part of class.
DEMERITS:

 Friend functions have access to private members of a class from outside the class which
violates the law of the data hiding.
 Friend functions cannot do any run time polymorphism in its members.

VIRTUAL FUNCTION:
A virtual function is a member function which is declared within a base class and is re-
defined (overridden) by a derived class. When you refer to a derived class object using a
pointer or a reference to the base class, you can call a virtual function for that object and
execute the derived class’s version of the function.

 Virtual functions ensure that the correct function is called for an object, regardless of
the type of reference (or pointer) used for function call.
 They are mainly used to achieve Runtime polymorphism
 Functions are declared with a virtual keyword in base class.
 The resolving of function call is done at runtime.

RULES FOR VIRTUAL FUNCTIONS:


1. Virtual functions cannot be static.
2. A virtual function can be a friend function of another class.
3. Virtual functions should be accessed using pointer or reference of base class type to
achieve runtime polymorphism.
4. The prototype of virtual functions should be the same in the base as well as derived class.
5. They are always defined in the base class and overridden in a derived class. It is not
mandatory for the derived class to override (or re-define the virtual function), in that case,
the base class version of the function is used.
6. A class may have virtual destructor but it cannot have a virtual constructor.
DYNAMIC BINDING:

Binding refers to the linking of a procedure call to code to be executed in response to


the call. Dynamic binding (also known as late binding) means that the code associated with a
given procedure call is not known until the time of the call at run-time. It associated with
polymorphism and inheritance. A function call associated with a polymorphic reference
depends on the dynamic type of that reference.

MESSAGE PASSING:

An object-oriented program consists of a set of objects that communicate with each


other. The process of programming in an object-oriented language, therefore, involves the
following basic steps:

1. Creating classes that define objects and their behaviour,


2. Creating objects from class definitions, and
3. Establishing communication among objects.

Objects communicate with one another be sending and receiving information much the
same way as people pass messages to one another.

MERITS OF OBJECT-ORIENTED PROGRAMMING:

 We can build the programs from standard working modules that communicate with one
another, rather than having to start writing the code from scratch which leads to saving of
development time and higher productivity,
 OOP language allows breaking the program into the bit-sized problems that can be solved
easily (one object at a time).
 The new technology promises greater programmer productivity, better quality of software
and lesser maintenance cost.
 OOP systems can be easily upgraded from small to large systems.
 It is possible that multiple instances of objects co-exist without any interference,
 It is very easy to partition the work in a project based on objects.
 It is possible to map the objects in problem domain to those in the program.
 The principle of data hiding helps the programmer to build secure programs which cannot
be invaded by the code in other parts of the program.
 By using inheritance, we can eliminate redundant code and extend the use of existing
classes.
 Message passing techniques is used for communication between objects which makes the
interface descriptions with external systems much simpler.
 The data-centered design approach enables us to capture more details of model in an
implementable form.

DEMERITS OF OBJECT ORIENTED PROGRAMMING:


 The length of the program developed using OOP language is much larger than the
procedural approach. Since the program becomes larger in size, it requires more time to
be executed that leads to slower execution of the program.
 We cannot apply OOP everywhere as it is not a universal language. It is applied only
when it is required. It is not suitable for all types of problems.
 Programmers need to have brilliant designing skill and programming skill along with
proper planning because using OOP is little bit tricky.
 OOPs take time to get used to it. The thought process involved in object-oriented
programming may not be natural for some people.
 Everything is treated as object in OOP so before applying it we need to have excellent
thinking in terms of objects.

POPULAR OOP LANGUAGE:

Object-oriented programming is not the right of any particular language. Like


structured programming, OOP concepts can be implemented using languages such as C and
Pascal. However, programming becomes clumsy and may generate confusion when the
programs grow large. A language that is specially designed to support the OOP concepts
makes it easier to implement them.
The languages should support several of the OOP concepts to claim that they are Object
Oriented. Depending upon the features they support, they can be classified into the following
two categories:

1. Object- based programming languages and


2. Object- Oriented Programming languages.

Object-based programming is the style of programming that primarily supports


encapsulation and object identify. Major features that are required for object-based
programming are:

 Data encapsulation
 Data hiding and access mechanisms
 Automatic initialization and clear-up of objects
 Operator overloading

Languages that support programming with objects are said to be object-based


programming languages. They do not support inheritance and dynamic binding. Ada is typical
object-based programming language.

Object-oriented programming incorporates all object –based programming features


along with two additional features, namely inheritance and dynamic binding. Object-Oriented
programming can therefore be characterized by following statement.

Object-based features + inheritance + dynamic binding

Languages that supports these features include C++,smalltalk, Object Pascal and Java.

APPLICATIONS OF OOP:

 Real-Time System design: Real-time system inherits complexities and makes it difficult to
build them. OOP techniques make it easier to handle those complexities.
 Hypertext and Hypermedia: Hypertext is similar to regular text as it can be stored,
searched, and edited easily. Hypermedia on the other hand is a superset of hypertext. OOP
also helps in laying the framework for hypertext and hypermedia.
 AI Expert System: These are computer application that is developed to solve complex
problems which are far beyond the human brain. OOP helps to develop such an AI expert
System
 Office automation System: These include formal as well as informal electronic systems
that primarily concerned with information sharing and communication to and from people
inside and outside the organization. OOP also help in making office automation principle.
 Neural networking and parallel programming: It addresses the problem of prediction
and approximation of complex-time varying systems. OOP simplifies the entire process by
simplifying the approximation and prediction ability of the network.
 Stimulation and modeling system: It is difficult to model complex systems due to varying
specifications of variables. Stimulating complex systems require modeling and
understanding interaction explicitly. OOP provides an appropriate approach for simplifying
these complex models.
 Object-oriented database: The databases try to maintain a direct correspondence between
the real world and database object in order to let the object retain it identity and integrity.
 Client-server system: Object-oriented client-server system provides the IT infrastructure
creating object-oriented server internet (OCSI) applications.
 CIM/CAD/CAM systems: OOP can also be used in manufacturing and designing
applications as it allows people to reduce the efforts involved. For instance, it can be used
while designing blueprints and flowcharts. So it makes it possible to produce these
flowcharts and blueprint accurately.

C++ AT A GLANCE:

C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form


programming language that supports procedural, object-oriented, and generic programming.

C++ is regarded as a middle-level language, as it comprises a combination of both high-


level and low-level language features.

C++ was developed by BJARNE STROUSTRUP starting in 1979 at Bell Labs in


Murray Hill, New Jersey, as an enhancement to the C language and originally named C with
Classes but later it was renamed C++ in 1983.
C++ is a superset of C, and that virtually any legal C program is a legal C++ program.

NOTE − A programming language is said to use static typing when type checking is performed
during compile-time as opposed to run-time.

USE OF C++:

 C++ is used by hundreds of thousands of programmers in essentially every application


domain.
 C++ is being highly used to write device drivers and other software that rely on direct
manipulation of hardware under real-time constraints.
 C++ is widely used for teaching and research because it is clean enough for successful
teaching of basic concepts.
 Anyone who has used either an Apple Macintosh or a PC running Windows has
indirectly used C++ because the primary user interfaces of these systems are written in
C++.

APPLICATIONS OF C++:

C++ is a versatile language for handling very large programs. It is suitable for virtually
any programming task including development of editors, compilers, databases, communication
systems and any complex real –life application systems.

 Since C++ allows us to create hierarchy-related object, we can build special object-
oriented libraries which can be used later by many programmers.
 While C++ is able to map the real-world problem property, the C part of C++ gives the
language the ability to get close to the machine-level details.
 C++ programs are easily maintainable and expandable. When a new feature needs to be
implemented, it is very easy to add to the existing structure of an object.
 It is expected that C++ will replace C as general-purpose language in the near future.

Some of the major applications that are used in C++ by major software vendors, sellers, and
giants are-
 Google: C++ is used for lots of google magic like Big table, Google file system,
Google Chromium browser, and MapReduce large cluster data processing are all
written in C++.
 Mozilla: Mozilla uses a subset of C++. C++ 14 is required to build Mozilla 59,
Mozilla Firefox, and Thunderbird email chat client are both written using C++.
 Microsoft: Lots of windows apps that you regularly use are written in C++, It features
tools for developing and debugging C++ code, especially code written for the DirectX,
Windows API, and .NET.
 Rockstar Games: Almost all major game companies use C++ due to its right speed on
bare metal. Many major game engines are fully written in C++ and leverage its speed
and OOPs capabilities.
 MongoDB: MongoDB is an open-source database, widely used as the back-end store
for web applications, as well as in large enterprises like Viacom, biotechnology giants,
and Disney.
 Games and Animations: C++ is used for developing games. It simplifies the
complexity of 3-Dimensional games and helps in optimizing the resources. C++
supports the multiplayer option with networking. It is preferable because it is very fast
in runtime and is mainly used in developing the suites of a game tool. It is widely used
in building real-time, image processing, visual effects, and mobile sensor applications,
modelling which is mainly coded in C++. This software is used for animation,
environments, motion graphics, and virtual reality. These virtual reality devices are the
most popular in today’s entertainment world.
 Media Access: C++ is also used for creating a media player, managing video files and
audio files, etc. An example is the Winamp Media player, which is developed in C++,
which allows users to enjoy music, access and share the videos and music files, etc.
 Compilers: It is known that C++language is compiled language this is the main reason
why most of the compilers are mainly written in C++ language only. The compilers
used for compiling other languages like C#, Java, etc. are mainly written in C++ only. It
is also used in developing these languages as well as C++ is platform-independent and
able to create a variety of software.
 Scanning: The applications such as film scanners or camera scanners are also
developed in the C++ language. It has been used for developing PDF technology for
print documentation, exchanging documents, publishing the documents, and archiving
the document as well.

C++ PROGRAM STRUCTURE:

To print : “Hello World”.

#include <iostream>
using namespace std;
// main() is where program execution begins.
int main() {
cout << "Hello World"; // prints Hello World
return 0;}

Various parts of the above program −

 The C++ language defines several headers, which contain information that is either
necessary or useful to your program. For this program, the header <iostream> is needed.
 The line using namespace std; tells the compiler to use the std namespace. Namespaces
are a relatively recent addition to C++.
 The next line '// main() is where program execution begins.' is a single-line comment
available in C++. Single-line comments begin with // and stop at the end of the line.
 The line int main() is the main function where program execution begins.
 The next line cout << "Hello World"; causes the message "Hello World" to be displayed
on the screen.
 The next line return 0; terminates main( )function and causes it to return the value 0 to
the calling process.

COMPILE AND EXECUTE C++ PROGRAM:

To save the file, compile and run the program. Please follow the steps given below −

 Open a text editor and add the code as above.


 Save the file as: [Link]
 Open a command prompt and go to the directory where you saved the file.
 Type 'g++ [Link]' and press enter to compile your code. If there are no errors in your
code the command prompt will take you to the next line and would generate [Link]
executable file.
 Now, type '[Link]' to run your program.
 You will be able to see ' Hello World ' printed on the window.
$ g++ [Link]
$ ./[Link]
Hello World

Make sure that g++ is in your path and that you are running it in the directory containing
file [Link].

SEMICOLONS AND BLOCKS IN C++:

In C++, the semicolon is a statement terminator. That is, each individual statement must
be ended with a semicolon. It indicates the end of one logical entity.

For example, following are three different statements −

x = y;
y = y + 1;
add(x, y);

A block is a set of logically connected statements that are surrounded by opening and
closing braces. For example −

{
cout << "Hello World"; // prints Hello World
return 0;
}

C++ does not recognize the end of the line as a terminator. For this reason, it does not
matter where you put a statement in a line. For example −
x = y;
y = y + 1;
add(x, y);

is the same as

x = y; y = y + 1; add(x, y);

UNIT 2

DATA TYPES:

Image 2: Data types in C++


PRIMITIVE BUILT-IN TYPES

C++ offers the programmer a rich assortment of built-in as well as user defined data
types. Following table lists down seven basic C++ data types −

Type Keyword
Boolean Bool
Character Char
Integer Int
Floating point Float
Double floating point Double
Valueless Void
Wide character wchar_t

Several of the basic types can be modified using one or more of these type modifiers −

 signed
 unsigned
 short
 long

The following table shows the variable type, how much memory it takes to store the value in
memory, and what is maximum and minimum value which can be stored in such type of
variables.

Type Typical Bit Width Typical Range


char 1byte -127 to 127 or 0 to 255
unsigned char 1byte 0 to 255
signed char 1byte -127 to 127
int 4bytes -2147483648 to 2147483647
unsigned int 4bytes 0 to 4294967295
signed int 4bytes -2147483648 to 2147483647
short int 2bytes -32768 to 32767
unsigned short int 2bytes 0 to 65,535
signed short int 2bytes -32768 to 32767
long int 8bytes -2,147,483,648 to 2,147,483,647
signed long int 8bytes same as long int
unsigned long int 8bytes 0 to 4,294,967,295
long long int 8bytes -(2^63) to (2^63)-1
unsigned long long int 8bytes 0 to 18,446,744,073,709,551,615
float 4bytes 3.4E-38 to 3.4E+38
double 8bytes 1.7E-308 to 1.7E+308
long double 12bytes 3.4E-4932 to 1.1E+4932
wchar_t 2 or 4 bytes 1 wide character

The size of variables might be different from those shown in the above table, depending
on the compiler and the computer you are using.

Endl;

Which inserts a new-line character after every line and << operator is being used to pass
multiple values out to the screen. We are also using sizeof() operator to get size of various data
types.

TYPEDEF DECLARATIONS

Create a new name for an existing type using typedef. Following is the simple syntax to
define a new type using typedef −

typedef type newname;

For example, the following tells the compiler that feet is another name for int −

typedef int feet;

Now, the following declaration is perfectly legal and creates an integer variable called distance −

feet distance;
DERIVED DATA TYPES

The data-types that are derived from the primitive or built-in data types are referred to as
Derived Data Types. These can be of four types namely:

1. Function: A function is a block of code or program-segment that is defined to perform a


specific well-defined task. A function is generally defined to save the user from writing the
same lines of code again and again for the same input. All the lines of code are put together
inside a single function and this can be called anywhere required. main() is a default function
that is defined in every program of C++.

Syntax:
FunctionType FunctionName(parameters)

2. Array: An array is a collection of items stored at continuous memory locations. The idea of

array is to represent many instances in one variable.

Syntax:
DataType ArrayName[size_of_array];

3. Pointers: Pointers are symbolic representation of addresses. They enable programs to


simulate call-by-reference as well as to create and manipulate dynamic data structures. It’s
general declaration in C/C++ has the format:

Syntax:
datatype *var_name;
4. Reference: When a variable is declared as reference, it becomes an alternative name for an
existing variable. A variable can be declared as reference by putting ‘&’ in the declaration.

USER – DEFINED DATATYPE:


STRUCTURE IN C++:
A structure is a user-defined data type in C/C++. A structure creates a data type that can
be used to group items of possibly different types into a single type. The ‘struct’ keyword is
used to create a structure.
Syntax:
struct structureName{

member1;

member2;

member3;

memberN;

};

Structures in C++ can contain two types of members:

 Data Member: These members are normal C++ variables. We can create a structure with
variables of different data types in C++.
 Member Functions: These members are normal C++ functions. Along with variables, we
can also include functions inside a structure declaration.
UNIONS IN C++:
A union is a type of structure that can be used where the amount of memory used is a key
factor.
 Similarly to the structure, the union can contain different types of data types.
 Each time a new variable is initialized from the union it overwrites the previous in C
language but in C++ we also don’t need this keyword and uses that memory location.
 This is most useful when the type of data being passed through functions is unknown, using
a union which contains all possible data types can remedy this problem.
 It is declared by using the keyword “union“.

ENUMERATED IN C++
Enum is the short name for enumeration. It is a user-defined data type. It is used to
define a list of options that can be selected. Once, enum is declared we cannot change its value,
the compiler will throw an error. Two enumerations cannot share the same names.
enum enumName{

member1;

member2;

member3;

memberN;

};
DIFFERENCE BETWEEN STRUCTURES AND UNION:
[Link] STRUCTURE UNION
1 A structure is defined with ‘struct’ A Union is defined with ‘Union’
keyword keyword.
2 All members of a structure can be The members of a union can be
manipulated simultaneously manipulated only one at a ime.
3 The size of a structure object is equal to The size of a union object is equal to the
the sum of the individual sizes of the size of largest member object.
member object.
4 Structure members are allocated distinct Union members share common memory
memory locations. space for their exclusive usage.
5 Structures are not considered as memory Unions are considered as memory
efficient in comparison to unions. efficient particularly in situations when
the members are not required to be
accessed simultaneously.
6 Structures in C++ behave just like a Unions retain their core functionality in
class. Almost everything that can be C++ with slight add-one like declaration
achieved with a class can also be done of anonymous unions.
with structures.

CHARACTER SET:
Character set is a set of valid characters that a language can recognise. A character
represents any letter, digits, or any other sign.

C++ has the following character set:

 Letters : A-Z, a-z


 Digits : 0-9
 Special Symbols : Space + - ∗ ⁄ ^ \ ( ) [ ] { } = != < > . ′ ″ $ , ; : % ! & _ # <= >= @
 White Spaces : Blank space, Horizontal tab (→), Carriage return (↵), Newline, Form feed
 Other Characters : C++ can process any of the 256 ASCII characters as data or as literals.
TOKENS:
A token is the smallest element of a program that is meaningful to the compiler. Tokens
can be classified as follows:

1. KEYWORDS:
Keywords are pre-defined or reserved words in a programming language. Each keyword
is meant to perform a specific function in a program. Since keywords are referred names for a
compiler, they can’t be used as variable names because by doing so, we are trying to assign a
new meaning to the keyword which is not allowed. You cannot redefine keywords. However,
you can specify the text to be substituted for keywords before compilation by using C/C++
preprocessor directives. C language supports 32 keywords which are given below:
Auto Double Int struct

Break Else Long switch


Case Enum Register typedef
Char Extern Return union
Const Float Short unsigned
continue For Signed void
default Goto Sizeof volatile
Do If Static while
While in C++ there are 31 additional keywords other than C Keywords they are:
asm bool catch class

const_cast Delete dynamic_cast explicit

export false friend inline

mutable Namespace New operator


Private Protected Public reinterpret_cast
static_cast template This throw

True Try Typeid typename


using virtual wchar_t
2. IDENTIFIERS:
Identifiers are used as the general terminology for the naming of variables, functions and
arrays. These are user-defined names consisting of an arbitrarily long sequence of letters and
digits with either a letter or the underscore (_) as a first character. Identifier names must differ
in spelling and case from any keywords. You cannot use keywords as identifiers; they are
reserved for special use. Once declared, you can use the identifier in later program statements
to refer to the associated value. A special kind of identifier, called a statement label, can be
used in goto statements.

There are certain rules that should be followed while naming c identifiers:
 They must begin with a letter or underscore (_).
 They must consist of only letters, digits, or underscore. No other special character is
allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first 31 characters are significant.
 main: method name.
 a: variable name.

3. CONSTANTS:
Constants are also like normal variables. But, the only difference is, their values can not
be modified by the program once they are defined. Constants refer to fixed values. They are
also called literals.
Constants may belong to any of the data type

SYNTAX:
const data_type variable_name; (or)
const data_type *variable_name;
Types of Constants:

1. Integer constants – Example: 0, 1, 1218, 12482


2. Real or Floating-point constants – Example: 0.0, 1203.03, 30486.184
3. Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal: (013)16 =
(19)10
4. Character constants -Example: ‘a’, ‘A’, ‘z’
5. String constants -Example: “Ramu”

4. STRINGS:
Strings are nothing but an array of characters ended with a null character (‘\0’). This null
character indicates the end of the string. Strings are always enclosed in double-quotes.
Therefore a character is enclosed with single quotes in C and C++.

DECLARATIONS FOR STRING :


 char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
 char string[20] = “geeksforgeeks”;
 char string [] = “geeksforgeeks”;
 when we declare char as “string[20]”, 20 bytes of memory space is allocated for holding
the string value.
 When we declare char as “string[]”, memory space will be allocated as per the requirement
during the execution of the program.

5. SPECIAL SYMBOLS:
The following special symbols are used in C having some special meaning and thus, cannot
be used for some other purpose.[] () {}, ; * = #
 Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls and function
parameters.
 Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
 Comma (, ): It is used to separate more than one statements like for separating parameters
in function calls.
 Colon(:): It is an operator that essentially invokes something called an initialization list.
 Semicolon(;): It is known as a statement terminator. It indicates the end of one logical
entity. That’s why each individual statement must be ended with a semicolon.
 Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
 Assignment operator(=): It is used to assign values and for the logical operation
validation.
 Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.

6. OPERATORS:
Operators are symbols that trigger an action when applied to C variables and other
objects. The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators can be
classified as follows:

 Unary Operators: Those operators that require only a single operand to act upon are
known as unary [Link] Example increment and decrement operators
 Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators are classified into :
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
 Ternary Operator: The operator that require three operands to act upon are called ternary
operator. Conditional Operator(?) is also called ternary operator.
Syntax: (Expression1)? expression2: expression3;
VARIABLES:

A variable is a name given to a memory location. It is the basic unit of storage in a


program.

 The value stored in a variable can be changed during program execution.


 A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
 In C++, all the variables must be declared before use.

VARIABLE DECLARATION:

// Declaring a single variable

type variable_name;

// Declaring multiple variables:

type variable1_name, variable2_name, variable3_name;

A typical variable declaration is of the form:

A variable name can consist of alphabets (both upper and lower case), numbers and the
underscore ‘_’ character. However, the name must not start with a number.

HERE,
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.

EXAMPLES:

// Declaring float variable

float simpleInterest;

// Declaring integer variable

int time, speed;

// Declaring character variable

char var;

DIFFERENCE BETWEEN VARIABLE DECLARATION AND


DEFINITION:

The variable declaration refers to the part where a variable is first declared or
introduced before its first use.
A variable definition is a part where the variable is assigned a memory location and a
value. Most of the time, variable declaration and definition are done together.

TYPES OF VARIABLES:
There are three types of variables based on the scope of variables in C++:

 Local Variables
 Instance Variables
 Static Variables
1. Local Variables: A variable defined within a block or method or constructor is called a
local variable.
 These variables are created when entered into the block or the function is called and
destroyed after exiting from the block or when the call returns from the function.
 The scope of these variables exists only within the block in which the variable is
declared. i.e. we can access this variable only within that block.
 Initialization of Local Variable is Mandatory.
2. Instance Variables: Instance variables are non-static variables and are declared in a class
outside any method, constructor or block.
 As instance variables are declared in a class, these variables are created when an object
of the class is created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If we do not
specify any access specifier then the default access specifier will be used.
 Initialization of Instance Variable is not Mandatory.
 Instance Variable can be accessed only by creating objects.
3. Static Variables: Static variables are also known as Class variables.
 These variables are declared similarly as instance variables, the difference is that static
variables are declared using the static keyword within a class outside any method
constructor or block.
 Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
 Static variables are created at the start of program execution and destroyed
automatically when execution ends.
 Initialization of Static Variable is not Mandatory. Its default value is 0
 If we access the static variable like the Instance variable (through an object), the
compiler will show the warning message and it won’t halt the program. The compiler
will replace the object name with the class name automatically.
 If we access the static variable without the class name, the Compiler will automatically
append the class name.

INSTANCE VARIABLE VS STATIC VARIABLE :

 Each object will have its own copy of the instance variable whereas we can only have one
copy of a static variable per class irrespective of how many objects we create.
 Changes made in an instance variable using one object will not be reflected in other objects
as each object has its own copy of the instance variable. In the case of static, changes will
be reflected in other objects as static variables are common to all objects of a class.
 We can access instance variables through object references and Static Variables can be
accessed directly using the class name.

Syntax for static and instance variables:


class Example

static int a; // static variable

int b; // instance variable

}
CONTROL FLOW STATEMENTS:

Control flow or flow of control is the order in which instructions, statements and function
calls being executed or evaluated when a program is running. The control flow statements are
also called as Flow Control Statements.
In C++, Control flow statements are mainly categorized in following types –

 Selection statements
 Iteration statements
 Jump statements

IMAGE3: C++ control statements

C++ SELECTION STATEMENTS:

In C++, Selection statements allow you to control the flow of the program during run time on the
basis of the outcome of an expression or state of a variable. Selection statements are also referred
to as Decision making statements. Selection statements evaluate single or multiple test
expressions which results in “TRUE” or “FALSE”. The outcome of the test expression/condition
helps to determine which block of statement(s) to execute if the condition
is “TRUE” or “FALSE” otherwise.
In C++, we have following selection statements –

 C++ If-else Statements


 C++ Switch Statements

C++ ITERATION STATEMENTS:

In C++, Iteration statements are used to execute the block of code repeatedly for a
specified number of times or until it meets a specified condition. Iteration statements are
commonly known as loops or looping statements.
In C++, we have following iteration statements available-

 C++ for loop


 C++ while loop
 C++ do while loop

C++ JUMP STATEMENTS:

Jump statements are used to alter or transfer the control to other section or statements in
your program from the current section.

In C++, we have following types of jump statements –

 C++ Break Statement


 C++ Continue Statement
 C++ goto Statement

All of the above jump statements cause different types of jumps.

C++ DECISION MAKING STATEMENTS:

There is case where we want a block of code to be executed when some condition is
satisfied. In C++, we have rich set of Decision Making Statement that enable computer to decide
which block of code to be executed based on some conditional choices. Decision making
statement statements is also referred to as selection statements. Decision making statement
evaluates single or multiple test expressions which results is “TRUE” or “FALSE”. The outcome
of the test expression/condition helps to determine which block of statement(s) to execute if the
condition is “TRUE” or “FALSE” otherwise.
In C++, we have following decision making statements –

 C++ if Statements
 C++ if else Statements
 C++ if else if Statements
 C++ Nested If Statements
 C++ Switch Case Statement

IMAGE 4: C++ Decision Making Statements

C++ IF STATEMENT:

If statement, allow a block of code to be executed only when a specified condition is true.
An if statement evaluates a boolean expression followed by one or more statements. The given
boolean expression results in a boolean value that can only be either true or false.
Syntax:-
if(condition){
// statements
}
Here, Condition is a Boolean expression that results in either True or False, if it results
in True then statements inside if body are executed, if it results in False then execution is skipped
from if body.

C++ IF ELSE STATEMENT:

In C++, when we want to execute a block of code when if condition is true and another
block of code when if condition is false, In such a case we use if…else statement.

Syntax:-
if(condition){

// statements

} else {

// statements

Here, Condition is a Boolean expression that results in either True or False, if it results
in True then statements inside if body are executed, if it results in False then statements inside
else body are executed.

C++ IF ELSE IF STATEMENT:

When we want to add multiple condition checks in single if else statement then by using
if else-if else statement we can easily add multiple conditions. In C++, if..else..if statement
allows us add alternative set of test conditions in if..else statement using else-if and
single else statements for if condition. In such way if..else..if statement is used to select one
among several blocks of code to be executed.
Syntax:-
if(condition1) {

// statement(s)}

else if(condition2){

// statement(s)}

else if(conditionN){

// statement(s)}

else {

// statement(s)}

C++ NESTED IF STATEMENT:

In C++, when there is an if statement inside another if statement then it is known as


nested if else. Nested if else can also be simplified using C++ Switch Case Statement.
Syntax:-
if(condition1) {

if(condition2){ // statements

} else {

// statements}}

else {

if(condition3){// statements

} else {// statements}}


C++ SWITCH CASE STATEMENT:

In C++, switch case statement is simplified form of the C++ Nested if else statement , it
helps to avoid long chain of if..else if..else statements. A switch case statement evaluates an
expression against multiple cases in order to identify the block of code to be executed.
Syntax:-
switch(expression){
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements
break;
}

C++ FOR LOOP:

For loop is used, to execute block of code nth times. In C++, basic for loop is similar as it
is in C. For loop takes a variable as iterator and assign it with an initial value, and iterate through
the loop body as long as the test condition is true.
Syntax:

for(Initialization; Condition; incr/decr){

// loop body

}
C++ WHILE LOOP

While loop will execute a block of statement as long as a test expression is true.

Syntax:

while(condition)

// loop body

C++ DO…WHILE LOOP:

The do…while statement executes loop statements and then test the condition for next
iteration and executes next only if condition is true.

Syntax:

do{

// loop body

} while(condition);
C++ CONTINUE STATEMENT:

In C++, the continue statement gives you way to skip over the current iteration of any
loop. When a continue statement is encountered in the loop, the rest of statements in the loop
body for current iteration and returns the program execution to the very first statement in the
loop body. It does not terminates the loop rather continues with the next iteration.

C++ BREAK STATEMENT:

In C++, break statement inside any loop gives you way to break or terminate the
execution of loop containing it, and transfers the execution to the next statement following the
loop. It is almost always used with if..else construct.

C++ GOTO STATEMENT:

In C++, goto statement is used to alter the normal execution of a program and transfer
control to a labeled statement in the same program. In a C++ program we can have multiple goto
and label statements, the goto statement is followed by a label name. Label is an identifier, which
can be any plain text and can be set anywhere in a C++ program above or below to goto
statement. When a goto statement is encountered, compiler transfers the control to
a label: specified with goto statement and begin execution from there.

ARRAYS:
An array is a collection of items stored at contiguous memory locations. The idea is to
store multiple items of the same type together. This makes it easier to calculate the position of
each element by simply adding an offset to a base value, i.e., the memory location of the first
element of the array (generally denoted by the name of the array). The base value is index 0
and the difference between the two indexes is the offset.

ARRAY’S SIZE:
In C language, the array has a fixed size meaning once the size is given to it, it cannot be
changed i.e. you can’t shrink it nor can you expand it. The reason was that for expanding if we
change the size we can’t be sure ( it’s not possible every time) that we get the next memory
location to us for free. The shrinking will not work because the array, when declared, gets
memory statically allocated, and thus compiler is the only one that can destroy it.

TYPES OF INDEXING IN AN ARRAY:


 0 (zero-based indexing): The first element of the array is indexed by a subscript of 0.
 1 (one-based indexing): The first element of the array is indexed by the subscript of 1.
 n (N-based indexing): The base index of an array can be freely chosen. Usually,
programming languages allowing n-based indexing also allow negative index values, and
other scalar data types like enumerations, or characters may be used as an array index.

TYPES OF ARRAYS:
1. One dimensional array (1-D arrays)
2. Multidimensional array

MULTIDIMENSIONAL ARRAY:
Multi-dimensional array can be termed as an array of arrays that stores homogeneous
data in tabular form. Data in multidimensional arrays are stored in row-major order.

The general form of declaring N-dimensional arrays is:


data_type array_name[size1][size2]....[sizeN];

 data_type: Type of data to be stored in the array.


 array_name: Name of the array
 size1, size2,… ,sizeN: Sizes of the dimension

FUNCTIONS:

Function is a group of statements that together perform a task. Every C++ program has at
least one function, which is main(), and all the most trivial programs can define additional
functions.
We can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is such that each function
performs a specific task.

A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.

The C++ standard library provides numerous built-in functions that your program can
call. For example, function strcat() to concatenate two strings, function memcpy() to copy one
memory location to another location and many more functions.

A function is known with various names like a method or a sub-routine or a procedure


etc.

DEFINING A FUNCTION:

The general form of a C++ function definition is as follows −

return_type function_name( parameter list ) {


body of the function
}

A C++ function definition consists of a function header and a function body. Here are all the
parts of a function −

 Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
 Function Body − The function body contains a collection of statements that define what
the function does.
FUNCTION DECLARATIONS:

A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.

A function declaration has the following parts −

return_type function_name( parameter list );

For the above defined function max(), following is the function declaration −

int max(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so
following is also valid declaration −

int max(int, int);

Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the top of the
file calling the function.

CALLING A FUNCTION:

Creating a C++ function, you give a definition of what the function has to do. To use a
function, you will have to call or invoke that function.

When a program calls a function, program control is transferred to the called function. A
called function performs defined task and when it’s return statement is executed or when its
function-ending closing brace is reached, it returns program control back to the main program.

To call a function, you simply need to pass the required parameters along with function
name, and if function returns a value, then you can store returned value.

FUNCTION ARGUMENTS:

If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.

While calling a function, there are two ways that arguments can be passed to a function –

SL.N Call Type & Description


o
1 Call by Value

This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no effect
on the argument.

2 Call by Pointer

This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.

3 Call by Reference

This method copies the reference of an argument into the formal parameter. Inside the
function, the reference is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.

By default, C++ uses call by value to pass arguments. In general, this means that code
within a function cannot alter the arguments used to call the function and above mentioned
example while calling max() function used the same method.

DEFAULT VALUES FOR PARAMETERS:

When you define a function, you can specify a default value for each of the last
parameters. This value will be used if the corresponding argument is left blank when calling to
the function.

This is done by using the assignment operator and assigning values for the arguments in
the function definition. If a value for that parameter is not passed when the function is called, the
default given value is used, but if a value is specified, this default value is ignored and the passed
value is used instead. Consider the following example −

INLINE FUNCTION:

Inline function is one of the important feature of C++. When the program executes the
function call instruction the CPU stores the memory address of the instruction following the
function call, copies the arguments of the function on the stack and finally transfers control to
the specified function. The CPU then executes the function code, stores the function return
value in a predefined memory location/register and returns control to the calling function. This
can become overhead if the execution time of function is less than the switching time from the
caller function to called function (callee). For functions that are large and/or perform complex
tasks, the overhead of the function call is usually insignificant compared to the amount of time
the function takes to run. However, for small, commonly-used functions, the time needed to
make the function call is often a lot more than the time needed to actually execute the
function’s code. This overhead occurs for small functions because execution time of small
function is less than the switching time.

C++ provides an inline functions to reduce the function call overhead. Inline function is
a function that is expanded in line when it is called. When the inline function is called whole
code of the inline function gets inserted or substituted at the point of inline function call. This
substitution is performed by the C++ compiler at compile time. Inline function may increase
efficiency if it is small.

The syntax for defining the function inline is:


inline return-type function-name(parameters)

// function code

Remember, inlining is only a request to the compiler, not a command. Compiler can
ignore the request for inlining. Compiler may not perform inlining in such circumstances like:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return statement doesn’t exist in function
body.
5) If a function contains switch or goto statement.

5) Inline functions may not be useful for many embedded systems. Because in embedded
systems code size is more important than speed.

6) Inline functions might cause thrashing because inlining might increase size of the binary
executable file. Thrashing in memory causes performance of computer to degrade.

UNIT 3

CLASSES AND OBJECT:

A class in C++ is the building block that leads to Object-Oriented programming. 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 C++ class is like a blueprint for an
object.

A Class is a user defined data-type which has data members and member functions.
 Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions defines
the properties and behavior of the objects in a Class.
 In the above example of class Car, the data member will be speed limit, mileage etc and
member functions can be apply brakes, increase speed etc.

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.
Defining Class and Declaring Objects
A class is defined in C++ using keyword class followed by the name of class. The body
of class is defined inside the curly brackets and terminated by a semicolon at the end.

DECLARING OBJECTS:
When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, you need to
create objects.
Syntax:
ClassName ObjectName;

Accessing data members and member functions: The data members and member
functions of class can be accessed using the dot(‘.’) operator with the object. For example if
the name of object is obj and you want to access the member function with the
name printName() then you will have to write [Link]() .
ACCESSING DATA MEMBERS:
The public data members are also accessed in the same way given however the private
data members are not allowed to be accessed directly by the object. Accessing a data
member depends solely on the access control of that data member.
This access control is given by Access modifiers in C++. There are three access
modifiers: public, private and protected.

// C++ program to demonstrate

// accessing of data members

#include <bits/stdc++.h>

using namespace std;

class Geeks

{ // Access specifier

public:

// Data Members

string geekname;

// Member Functions()

void printname()
{

cout << "Geekname is: " << geekname;

};

int main() {

// Declare an object of class geeks

Geeks obj1;

// accessing data member

[Link] = "Abhi";

// accessing member function

[Link]();

return 0;

MEMBER FUNCTIONS IN CLASSES


There are 2 ways to define a member function:

 Inside class definition


 Outside class definition
To define a member function outside the class definition we have to use the scope
resolution :: operator along with class name and function name.

// C++ program to demonstrate function

// declaration outside class

#include <bits/stdc++.h>

using namespace std;

class Geeks

public:

string geekname;

int id;

// printname is not defined inside class definition

void printname();
// printid is defined inside class definition

void printid()

cout << "Geek id is: " << id;

};

// Definition of printname using scope resolution operator ::

void Geeks::printname()

cout << "Geekname is: " << geekname;

int main() {

Geeks obj1;

[Link] = "xyz";

[Link]=15;
// call printname()

[Link]();

cout << endl;

// call printid()

[Link]();

return 0;

Note that all the member functions defined inside the class definition are by
default inline, but you can also make any non-class function inline by using keyword inline
with them. Inline functions are actual functions, which are copied everywhere during
compilation, like pre-processor macro, so the overhead of function calling is reduced.
Note: Declaring a friend function is a way to give private access to a non-member function.
DATA HIDING:

In simple words, data hiding is an object-oriented programming technique of hiding


internal object details i.e. data members. Data hiding guarantees restricted data access to class
members & maintain object integrity.

FRIEND CLASS:

A friend class can access private and protected members of other class in which it is
declared as friend. It is sometimes useful to allow a particular class to access private members
of other class.
For example, a LinkedList class may be allowed to access private members of Node.
A friend class can access both private and protected members of the class in which it has been
declared as friend.

FRIEND FUNCTION:
Like friend class, a friend function can be given a special grant to access private and
protected members. A friend function can be:
a) A member of another class
b) A global function

 A friend function is a special function in C++ which in-spite of not being member function
of a class has privilege to access private and protected data of a class.
 A friend function is a non member function or ordinary function of a class, which is
declared as a friend using the keyword “friend” inside the class. By declaring a function as
a friend, all the access permissions are given to the function.
 The keyword “friend” is placed only in the function declaration of the friend function and
not in the function definition.
 When friend function is called neither name of object nor dot operator is used. However it
may accept the object as argument whose value it want to access.
 Friend function can be declared in any section of the class i.e. public or private or
protected.
Syntax :

class <class_name>

friend <return_type> <function_name>(argument/s); };

Following are some important points about friend functions and classes:
1) Friends should be used only for limited purpose. Too many functions or external classes are
declared as friends of a class with protected or private data, it lessens the value of
encapsulation of separate classes in object-oriented programming.
2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A
automatically.
3) Friendship is not inherited.
4) The concept of friends is not there in Java.

MERITS:
 A friend function is able to access members without the need of inheriting the class.
 Friend function acts as a bridge between two classes by accessing their private data.
 It can be used to increase the versatility of overloaded operator.
 It can be declared either in the public or private or protected part of class.

DEMERITS:

 Friend functions have access to private members of a class from outside the class which
violates the law of the data hiding.
 Friend functions cannot do any run time polymorphism in its members.

CONSTRUCTORS:
Constructor is a member function of class, whose name is same as the class.

A constructor is a special type of member function of a class which initializes objects of


a class. In C++, Constructor is automatically called when object(instance of class) is created.

Constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructors.

Constructor does not have a return value, hence they do not have a return type.

PROTOTYPE OF CONSTRUCTORS:

<class-name> (list-of-parameters);

Constructors can be defined inside or outside the class declaration:-


1. Syntax for defining the constructor within the class:

<class-name> (list-of-parameters)

// constructor definition

2. Syntax for defining the constructor outside the class:

<class-name>: :<class-name> (list-of-parameters){

// constructor definition}

CHARACTERISTICS OF CONSTRUCTOR:
• The name of the constructor is same as its class name.
• Constructors are mostly declared in the public section of the class though it can be declared
in the private section of the class.
• Constructors do not return values; hence they do not have a return type.
• A constructor gets called automatically when we create the object of the class.
• Constructors can be overloaded.
• Constructor can not be declared virtual.

TYPES OF CONSTRUCTORS:
Default Constructors: Default constructor is the constructor which doesn’t take any argument.
It has no parameters.
It is also called a zero argument constructor.

Note: Even if we do not define any constructor explicitly, the compiler will automatically
provide a default constructor implicitly

Parameterized Constructors: It is possible to pass arguments to constructors. Typically,


these arguments help initialize an object when it is created. To create a parameterized
constructor, simply add parameters to it the way you would to any other function. When you
define the constructor’s body, use the parameters to initialize the object.
Note: when parameterized constructor is defined and no default constructor is defined
explicitly, the compiler will not implicitly call the default constructor and hence creating a
simple object as
Student s;
Will flash an error

When an object is declared in a parameterized constructor, the initial values have to be passed
as arguments to the constructor function. The normal way of object declaration may not work.
The constructors can be called explicitly or implicitly.

Example e = Example(0, 50); // Explicit call

Example e(0, 50); // Implicit call

USES OF PARAMETERIZED CONSTRUCTOR:

1. It is used to initialize the various data elements of different objects with different values
when they are created.
2. It is used to overload constructors.

Copy Constructor: A copy constructor is a member function which initializes an object using
another object of the same class.
Whenever we define one or more non-default constructors ( with parameters ) for a class, a
default constructor( without parameters ) should also be explicitly defined as the compiler will
not provide a default constructor in this case. However, it is not necessary but it’s considered
to be the best practice to always define a default constructor.

Copy constructor takes a reference to an object of the same class as an argument.

Sample(Sample &t)
{
id=[Link];
}
DESTRUCTOR:
Destructor is also a special member function like constructor. Destructor destroys the
class objects created by constructor. Destructor has the same name as their class name
preceded by a tiled (~) symbol. It is not possible to define more than one destructor. The
destructor is only one way to destroy the object create by constructor. Hence destructor can-not
be overloaded. Destructor neither requires any argument nor returns any value. It is
automatically called when object goes out of scope. Destructor release memory space
occupied by the objects created by constructor. In destructor, objects are destroyed in the
reverse of an object creation.

Syntax for defining the destructor within the class


~ <class-name>()
{

Syntax for defining the destructor outside the class


<class-name>: : ~ <class-name>()
{

CHARACTERISTICS OF A DESTRUCTOR:-
1. Destructor is invoked automatically by the compiler when its corresponding constructor
goes out of scope and releases the memory space that is no longer requires by the program.
2. Destructor neither requires any argument nor returns any value therefore it cannot be
overloaded.
3. Destructor cannot be declared as static and const;
4. Destructor should be declared in the public section of the program.
5. Destructor is called in the reverse order of its constructor invocation.

CONSTRCTOR OVERLOADING:
In C++, We can have more than one constructor in a class with same name, as long as each has
a different list of arguments. This concept is known as Constructor Overloading and is quite
similar to function overloading.

 Overloaded constructors essentially have the same name (exact name of the class) and
differ by number and type of arguments.
 A constructor is called depending upon the number and type of arguments passed.
 While creating the object, arguments must be passed to let compiler know, which
constructor needs to be called.

ORDER OF CONSTRCTOR AND DESTRUCTOR:


Create an object of a class, the default constructor of that class is invoked automatically
to initialize the members of the class.

If we inherit a class from another class and create an object of the derived class, it is
clear that the default constructor of the derived class will be invoked but before that the default
constructor of all of the base classes will be invoke, i.e the order of invocation is that the base
class’s default constructor will be invoked first and then the derived class’s default constructor
will be invoked.

when a class is inherited , the data members and member functions of base class comes
automatically in derived class based on the access specifier but the definition of these members
exists in base class only. So when we create an object of derived class, all of the members of
derived class must be initialized but the inherited members in derived class can only be
initialized by the base class’s constructor as the definition of these members exists in base class
only. This is why the constructor of base class is called first to initialize all the inherited
members.

ORDER OF CONSTRUCTOR CALL FOR MULTIPLE INHERITANCES:


For multiple inheritances order of constructor call is, the base class’s constructors are
called in the order of inheritance and then the derived class’s constructor.
To call the parameterized constructor of base class when derived class’s parameterized
constructor is called, you have to explicitly specify the base class’s parameterized constructor
in derived class

You might also like