KEMBAR78
Unit-1 C++ | PDF | Object Oriented Programming | Pointer (Computer Programming)
0% found this document useful (0 votes)
24 views35 pages

Unit-1 C++

The document discusses procedural programming and object-oriented programming (OOP), highlighting their definitions, key features, advantages, and disadvantages. Procedural programming focuses on procedures and routines, while OOP emphasizes objects and data encapsulation, inheritance, and polymorphism. It also compares both paradigms and introduces C++ as a prominent language for OOP, detailing its applications and features.

Uploaded by

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

Unit-1 C++

The document discusses procedural programming and object-oriented programming (OOP), highlighting their definitions, key features, advantages, and disadvantages. Procedural programming focuses on procedures and routines, while OOP emphasizes objects and data encapsulation, inheritance, and polymorphism. It also compares both paradigms and introduces C++ as a prominent language for OOP, detailing its applications and features.

Uploaded by

rashmitap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Procedure – oriented programming

What is Procedural Programming?


Procedural programming is a programming language derived from structure programming
and based on the concept of calling procedure.
The procedures are the functions, routines, or subroutines that consist series of steps to be
carried out in the C++ OOPs concept.
Procedural programming uses a linear top-down approach during the design of the program.

 Key Features of Procedural Programming


 OOPs concepts in C++ have some key features of procedural programming.

 Predefined Functions: The system libraries already define these functions. To build
error-free code, a programmer will reuse the existing code in the system
libraries. charAt() is an example of a pre-defined function that searches for a character
position in a string.
 Local Variable: In programming, a variable is used only within the routine or
function it is defined in. When the function is finished and control is returned to the part of
the program that called it, the local variables no longer exist.
 Global Variable: A global variable is a variable that is declared in the global scope.
In other words, a variable is declared outside every other function defined in the code.
 Modularity: When two different systems have two distinct jobs at hand but are
grouped to perform a bigger job first, this is referred to as modularity. Modularity is a
powerful tool for reducing the complexity of systems.
 Parameter Passing: It‘s a mechanism to pass parameters to procedures, functions, or
routines. Parameter passing can be done through pass-by-value and pass-by-reference.

 Languages Used in Procedural Programming


The languages used in Procedural Programming are
FORTRAN, ALGOL, COBOL, BASIC, Pascal, and C.

 Advantages of Procedural Programming


 It is good for general-purpose programming.
 We can access the same code at different points in the software program without
repeating it.
 The memory need is also reduced by using the Procedural Programming technique.
 Disadvantages of Procedural Programming
 The code reusability feature is not present in procedural-oriented programming. We
have to rewrite the same programming code many times.
 Difficult to relate to real-world objects.
 We can not perform operations like encapsulation, inheritance, etc.

Object - Oriented Programming Paradigm


 object – oriented approach is to remove some of the flaws encountered
in the procedural approach.
 OOP allows decomposition of a problem into a number of entities
called objects
 and then builds data and functions around these objects.
 The organization of data and functions in object-oriented programs is
shown in following figure.
 The data of an object can be accessed only by the functions associated
with that object; however, functions of one object can access the
functions of other objects.

Organization of Data and Functions in OOP


Some of the striking features of object - oriented
programming are described as follows.
1. Emphasis is on data rather than procedure.
2. Programs are divided into what are known as objects.
3. Data structures are designed such that they characterize the objects.
4. Functions that operate on the data of an object are tied together
in the data structure.
5. Data is hidden and cannot be accessed by external functions.
6. Objects may communicate with each other through functions.
7. New data and functions can be easily added whenever necessary.
8. Follows bottom-up approach in program design.

―Object Oriented programming as an approach that provides a


way of modularizing programs by creating partitioned memory
area for both data and functions that can be used as templates
for creating copies of such modules on demand.”

Object-Oriented Programming (OOP)


What Is Object-Oriented Programming (OOP)?
A programming model is based upon the concepts of objects, or where everything is
represented as an object.
Basic Object-Oriented Programming (OOPS) Concept
Object-oriented programming aims to implement real-world entities in programming, such
as inheritance, abstraction, polymorphism, and so on.
Some C++ OOPs concepts that act as the basic building block of OOPs are:
 Object
 Class
 Encapsulation
 Abstraction
 Polymorphism
 Inheritance
 Dynamic Binding
 Message Passing
 Object:
 OOPs concept in C++ has an object which is an entity with some characteristics
and behaviour or anything that exists physically in the world, like a dog, a pen,
a pencil, etc.
 An object is an instance of the class. In Object-Oriented Programming, when a
class is defined, no memory is allocated, but when an object is created,
the memory is allocated.
 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 the user defined data such as vectors, time and lists
fruit mango;
will create an object mango belonging to the class fruit.
 Class:
 In the C++ OOPs concept, a class is a blueprint of the object.
 When you define a class, you define a blueprint for an object.
 A class contains data members (variables) and member functions.
 Classes are user-defined data types and behave like the built-in types
of a programming language.
 Consider the class of Person. There may be many people with different names and
heights, but they all share some common properties.
 So here, the person is the class, and age, gender, and occupation are their
properties.
 Together, these data members and member functions define the properties and
behaviour of the objects in a class.
 OOPs concept in C++ has a class defined by the keyword class followed by the
name of the class.
 The body of the class is defined inside the curly brackets and terminated by the
semicolon at the end.
fruit mango;
will create an object mango belonging to the class fruit.
 Encapsulation:
 The wrapping up of data and functions into a single unit called class is known as
encapsulation.
 More technically, encapsulation means placing the data and the functions that work on
that data in a single place. Like, a capsule is wrapped with different medicines.
 Assume you have an account in the bank.
 They define the balance variable as private to protect your account and ensure that no
one can see your account balance.
 The person who needs to check his account balance will only be able to access private
members via methods defined inside that class, and this method will demand your
account holder's name and password for authentication.
 As a result, we can achieve security by using the principle of data hiding.
 This is known as encapsulation.
 Abstraction:
 In the C++ OOPs concept, abstraction is the most useful and necessary feature.
 Abstraction means avoiding unnecessary and irrelevant information and only showing
the specific details of what users want to see.
 Abstraction refers to the act of representing essential features without including
the background details or explanations.
 In C++, we use abstract classes and interfaces to achieve abstraction.
 Every time you log into your email account (Gmail, Yahoo, Hotmail, or official mail),
many processes occur in the backend. You do not have any control over how
the password is verified, which keeps it safe from misuse.
 Polymorphism:
 In the C++ OOPs concept, polymorphism means taking more than one form.
 In the C++ OOPs concept, we use Operator overloading and Function overloading to
achieve polymorphism.
 Operator Overloading: The process of making an operator exhibit different
behaviours in different instances is known as Operator overloading.
 Function Overloading: When a single function name is used to execute many tasks,
this is known as function overloading.
 Suppose we have written a function that adds some integers.
 Sometimes there are two integers, and sometimes there are three.
 We can write the addition method with the same name but with different parameters,
and we will call these methods according to the parameters.

 Inheritance:
 Inheritance is the process by which objects of one class acquire the properties of
another class.
 It supports the concept of hierarchical classification.
 It helps to reduce the code size.
 Inheritance is the process in which two classes have is-a relationship among each
other and objects of one class acquire properties and features of the other class.
 The class which inherits the features is known as the child class, and the class whose
features it inherited is called the parent class.
 For example, Class Vehicle is the parent class, and Class Bus, Car, and Bike are child
classes.
Dynamic Binding:
 Binding refers to the linking of a procedure call to the code to be executed in
response to the call.
 Dynamic binding also known as late binding means that the code associated with
a give procedure call is not known until the time of the function call at run time.
 It is associated with polymorphism and inheritance.
 Message Passing:
 an object-oriented program consists of a set of objects that communicate
with each other.
 The process of programming in object-oriented language 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 by sending and receiving
information much the same way as people pass messages to one
another. The concept of message passing makes it easier to talk about
building systems .
 A message for an object is a request for execution of a procedure and
therefore will invoke a function in the receiving object that generates the
desired result. Message passing involves specifying the name of the
object, the name of the function – message and the information to be
sent. For example

employee . salary (name ) ;

Object Message Information


Objects have a life cycle. They can be created and destroyed. Communication with an
object is feasible as long as it is alive.
Languages Used in Object-Oriented Programming
The languages used in object-oriented programming are Java, C++, C#, Python, PHP,
JavaScript, Ruby, Perl, Objective-C, Dart, Swift, and Scala.
Advantages of Object-Oriented Programming (OOP)
 It helps in data hiding, keeping the data and information safe from leaking or
exposure.
 Because OOPs provide reusability to the code, we can use a class many times.
 In OOPs, it is easy to maintain code as there are classes and objects, which help in
making it easy to maintain rather than restructure.
Disadvantages of Object-Oriented Programming (OOP)
 As OOPs programs are large, they need more time to run, resulting in slower
execution.
 OOP is not a universal language, so we can only use it in some places. It is only used
when necessary. It is not appropriate for all sorts of issues.
 Everything is treated as an object in OOP, so before applying it, we need to think
about objects well.
Procedural Programming vs. Object-Oriented
Programming
On the basis
Procedural Programming Object-oriented programming
of
In Object-Oriented Programming, a
In procedural programming, we
programming model is based upon
break down a task into variables and
Definition the concepts of objects, or where
routines. After that, it is carried out
everything is represented as an
every step one by one.
object.
Object-Oriented Programming is
Procedural programming is less
secure because data hiding is
Security secure than Object-Oriented
possible in OOPs due to
Programming.
abstraction.
Procedural programming follow top- Object-Oriented Programming
Approach
down approach follow bottom-up approach
Procedural programming is
Orientation It is Object-oriented
structure/procedure-oriented
Private, Public, and Protected are
Access No access modifiers in Procedural
the access modifiers in Object-
Modifiers programming.
Oriented Programming.
Due to Inheritance, the concept of
Code No code reusability in Procedural
code reusability exists in Object-
Reusability programming.
Oriented Programming.
On the basis
Procedural Programming Object-oriented programming
of
There exists a concept of virtual
Virtual In Procedural programming, there is
classes in Object-Oriented
Class no concept of virtual classes.
Programming.
Object-Oriented Programming has
In procedural programming,
Overloading a concept of function overloading
overloading is not possible.
and operator overloading.
In Procedural programming, the In Object-Oriented Programming, a
Program
program is divided into small program is divided into small
Division
functions. objects.
Examples of object-oriented
Examples of procedural
programming are Java, C++, C#,
programming are FORTRAN,
Examples Python, PHP, JavaScript, Ruby,
ALGOL, COBOL, BASIC, Pascal,
Perl, Objective-C, Dart, Swift, and
and C.
Scala.

Benefits of OOPs:
OOP offers several benefits to both the program designer and user.
Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
 The principle of data hiding helps the programmer to build secure programs that cannot
be invaded by code on other parts of the program.
 It is possible to have multiple instances of on object to co-exist without any interference.
 It is possible to map objects in the problem domain to those objects in the program.
 It is easy to partition the work in a project based on objects.
 Object-oriented systems can be easily upgraded from small to large systems.
 Message passing techniques for communication between objects makes the interface
descriptions with external systems much simpler.
 Software complexity can be easily managed.
Applications of OOP:
Applications of OOP are beginning to gain importance in many areas.
The most popular application of object-oriented programming, up to now, has been in the
area
of user interface design such as windows.
The other areas for application of OOP includes:
 Real-time systems
 Simulation and modelling
 Object-oriented databases
 Hypertext, hypermedia and expertext
 AI and expert systems
 Neural networks and parallel programming
 Decision support and office automation systems
 CIM/CAM/CAD systems.
What is C++?
 C++ is an object-oriented programming language developed by Bjarne Stroustrup at
AT & T Bell Laboratories in New Jersey, USA, in 1980.
 It is developed from Simula67 and C programming language.
 The new fundamental is class in C++ programming language other than C so it was
given name ‗C with Classes‘ for C++.
 But in 1983 from the increment operator (++) of C language the new name was given
C++.
 In 1997 ANSI (American National Standard Institute) standardized C++.
 C++ is super-set of C and it is similar to C language.
 Most important facilities provided by C++ over C are: Class, Inheritance, function
overloading and Operator overloading.
 C language uses top-down structure of programming while C++ uses bottom-up
structure.
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.
Those lists of applications are the following:
 Google: We can say most of the components of Google are running with the
help of the C++ programming language. From the Chrome Browser to the
Google File system everywhere there is a use of C++ programming language.
 Mozilla: Mozilla is another important organization that is using the C++
programming language as the driving force. The Firefox browser is running
with the help of the C++ programming language. Even the email & client
connection has been done with the C++ programming language.
 Microsoft: We have already discussed the presence of C++ programming
language in the products of Microsoft. Even the Windows operating system has
some components which are running with the help of the C++ programming
language.
 MongoDB: MongoDB is an open-source application that has a major
contribution to the database management system. The back end of the
MongoDB application uses the C++ programming language as the key element.
 Scanner: All the scanner application is executed with the help of the C++
programming language. It might be scanning with the help of the mobile
camera also. But the presence of the C++ programming language is inevitable
when we will do some modifications to the scanned document.
Input Output Operators
Input operator:
 C++ provides the operator >> to get input. It extracts the value through the keyboard
and assigns it to the variable on its right; hence, it is called as “Stream
extraction” or “get from” operator.
 It is a binary operator i.e., it requires two operands. The first operand is the pre-
defined identifier cin (pronounced as C-In) that identifies keyboard as the input
device. The second operand must be a variable.

To receive or extract more than one value at a time, >> operator should be used for each
variable. This is called cascading of operator.
Example:
• cin >> num;
Pre-defined object cin extracts a value typed on keyboard and stores it in variable num.
• cin >>x >> y;
 This is used to extract two values. cin reads thefirst value and immediately assigns
that to variable x; next, it reads the second value which is typed after a space and
assigns that to y. Space is used as a separator for each input.
Output Operator:
 C++ provides << operator to perform output operation. The operator << is called
the “Stream insertion” or “put to” operator. It is used to send the strings or values
of the variables on its right to the object on its left. << is a binary operator.
 The first operand is the pre-defined identifier cout (pronounced as C-Out) that
identifies monitor as the standard output object. The second operand may be a
constant, variable or an expression.
To send more than one value at a time, << operator should be used for each constant/
variable/expression. This is called cascading of operator.
Example:
• cout << ―Welcome‖;
Pre-defined object cout sends the given string ―Welcome‖ to screen.
• cout << ―The sum = ― << sum;
• cout <<―\n The Area: ― <<3.14*r*r;
\n – is a non graphical character constant to feed a new line.
• cout << a + b ;
Cascading of I/O operators
The multiple use of input and output operators such as >> and << in a single statement is
known as cascading of I/O operators.
Cascading cout:
int Num=20;
cout << ―A=‖ << Num;
Cascading cin - Example:
cout >> ―Enter two number: ‖;
cin >> a >> b;
Structure of C++ Program
. The structure of the program written in C++ language is as follows:

Include Files

Class Declaration

Member Function Definitions

Main Function Program


Include Files:
 In C++ program, first section is the include section
 It contains pre-processor statements to include various header (library) files.
 This enables the programmer to use standard input, output, and error facilities that are
provided only through the standard streams defined in <iostream>.
 These standard streams process data as a stream of characters, that is, data is read and
displayed in a continuous flow.
 The standard streams defined in <iostream> are listed here.

#include<iostream>

Namespaces:
 A namespace permits grouping of various entities like classes, objects, functions, and
various C++ tokens, etc. under a single name.
 Any user can create separate namespaces of its own and can use them in any other
program.
 In the below snippets, namespace std contains declarations for cout, cin, endl, etc.
statements.
using namespace std;
 Namespaces can be accessed in multiple ways:
o using namespace std;
o using std :: cout;
Class Declaration Section:
 After the include section there is class declaration section.
 In class declaration we are defining class, its member variable and declaration for the
member function.
 This is also optional section.
 You can create your C++ program without class but to use object oriented features,
class is necessary.

Function Declaration Section:


• It contains all the functions which our main functions need.
• Usually, this section contains the User-defined.
• This part of the program can be written after the main function but for this, write the
function prototype in this section for the function which for you are going to write
code after the main function.
Main Function:
 The main function tells the compiler where to start the execution of the program.
The execution of the program starts with the main function.
 All the statements that are to be executed are written in the main function.
 The compiler executes all the instructions which are written in the curly
braces {} which encloses the body of the main function.
As soon as all the instructions in main () execute, the control passes out of main ( ), and
terminates the whole program and return a value to the operating system.
By default, main () in C++ returns an int value to the operating system. Thus, main () must
end with the return 0 statement. A return value zero denotes success and a non-zero value
denotes failure or error.
Introduction of namespace

Namespace

 Namespace is one of the new features in this language. It allows the grouping of
different entities such as classes, objects, functions and a variety of C++ tokens, etc.,
under a single name.
What is a Namespace?
 Namespaces provide a method to avoid name conflicts in a project.
 Namespaces in C++ are used as additional information to differentiate two or more
variables, functions, or classes having the same names.
Creation of Namespaces
 Creating a namespace in C++ is similar to creating a class.
 We use the keyword namespace followed by the name of the namespace to define a
namespace in C++.
Namespace MyNamespace
{
// Function, class, and variable declarations.
}
 The C++ Standards Committee has rearranged the entities of the standard library under a
namespace known as std.
 The entities of a namespace can be accessed in several ways which are as follows:
 By specifying the using directive
using namespace std;
cout<<“Hello World”;
 By specifying the full member name
std: :cout<<“Hello World”;
 By specifying the using-declaration
using std:: cout;
cout<<“Hello World”;
 As soon as the new-style header includes, its contents include in the std namespace.
Thus, all modern C++ compilers support these statements.
#include<iostream>
using namespace std;
 But, some old compilers may not support these statements. In this scenario, these single
statements replace the statements.
#include<iostream.h>
C++ Data Types
 All variables use data type during declaration to restrict the type of data to be stored.
 Whenever a variable is defined in C++, the compiler allocates some memory for that
variable based on the data type with which it is declared.
 Every data type requires a different amount of memory.
 Data types specify the size and types of values to be stored.
C++ supports the following data types:
1. Primary or Built-in or Fundamental data type or Basic data type
2. Derived data types
3. User-defined data types

Primitive(Basic) Data Types


 Integer: The keyword used for integer data types is int. Integers typically
require 4 bytes of memory space and range from -2147483648 to 2147483647.
 Character: Character data type is used for storing characters. The keyword used
for the character data type is char. Characters typically require 1 byte of
memory space and range from -128 to 127 or 0 to 255.
 Boolean: Boolean data type is used for storing Boolean or logical values. A
Boolean variable can store either true or false. The keyword used for the
Boolean data type is bool.
 Floating Point: Floating Point data type is used for storing single-precision
floating-point values or decimal values. The keyword used for the floating-point
data type is float. Float variables typically require 4 bytes of memory space.
 Double Floating Point: Double Floating Point data type is used for storing
double-precision floating-point values or decimal values. The keyword used for
the double floating-point data type is double. Double variables typically require
8 bytes of memory space.
 void: Void means without any value. void data type represents a valueless entity.
A void data type is used for those function which does not return a value.
 Wide Character: Wide character data type is also a character data type but this
data type has a size greater than the normal 8-bit data type. Represented
by wchar_t. It is generally 2 or 4 bytes long.
Datatype Modifiers
As the name suggests, datatype modifiers are used with built-in data types to modify the
length of data that a particular data type can hold.
Data type modifiers available in C++ are:
 Signed
 Unsigned
 Short
 Long
Type Bytes Range
Char 1 -128 to 127
Unsigned char 1 0 to 255
Signed char 1 -128 to 127
Int 2 -32768 to 32767
Unsigned int 2 0 to 65535
Signed int 2 -32768 to 32767
Short int 2 -32768 to 32767
Unsigned short int 2 0 to 65535
Signed short int 2 -32768 to 32767
Long int 4 -2147483648 to 147483647
Signed long int 4 -2147483648 to 147483647
Unsigned long int 4 0 to 4294967295
Float 4 3.4E-38 to 3.4 E+308
Double 8 1.7E-308 to 1.7E+308
Long double 10 3.4E-4932 to 1.1E+4932

Derived Data Types


The data-types that are derived from the primitive or built-in datatypes are referred to as
Derived Data Types. These can be of four types namely:
 Function
 Array
 Pointers
 References
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)

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];
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.
Syntax:
datatype *var_name;
Example:
int *ptr;

 ptr points to an address which holds int data

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

User defined Data Types in C++


The data types that are defined by the user are called the derived datatype or user-defined
derived data type.
These types include:
 Class
 Structure
 Union
 Enumeration
 Typedef defined DataType

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.
 A class is like a blueprint for an object.
Syntax:
Structure:
 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.
Syntax:
struct structurename {
data member…
data memer function..
};
Union:
 Like Structures, union is a user defined data type.
 In union, all members share the same memory location.
 For example in the following C program, both x and y share the same location. If we
change x, we can see the changes being reflected in y.

Enumeration:
 Enumeration (or enum) is a user defined data type in C.
 It is mainly used to assign names to integral constants, the names make a program
easy to read and maintain.
Syntax:
enum State {Working = 1, Failed = 0};
Typedef :
 C++ allows you to define explicitly new data type names by using the keyword
typedef. Using typedef does not actually create a new data class, rather it defines a
name for an existing type.
 This can increase the portability(the ability of a program to be used across different
types of machines; i.e., mini, mainframe, micro, etc; without much changes into the
code)of a program as only the typedef statements would have to be changed.
 Using typedef one can also aid in self-documenting code by allowing descriptive
names for the standard data types.
Syntax:
typedef type name;

where type is any C++ data type and name is the new name for this data type.
Symbolic Constants
There are two ways of creating symbolic constants in C++.
 Using the qualifier const and
 Using a set of integer constants using enum keyword.
 In both C and C++ any value declared as const can not be modified by the
program in any way.
 However, there are some differences in implementation.
 In C++, we can use const in a constant expression, such as
const int size = 10;
char name [size];
 This would be illegal in C. const allows us to create typed constant instead
of having to use #define to create constants that have no type information.
 if we use the const modifier alone it defaults to int. For example
const size = 10;
Means const int size = 10;
 The named constants are just like variables except that their values cannot
be changed
 C++ requires a const to be initialized.
 ANSI C does not require an initialize.

Another method of naming integer constants is by enumeration as under;
enum { X. Y. Z};
This defines X, Y and Z as integer constants with values 0, 1, and 2 respectively.
This is equivalent to:
const x = 0; const y = 1; const z = 2;

We can also assign values to x, y, and z explicitly. Example: enum(x = 100, y = 50,
z= 200);
Such values can be any integer values.

Type Compatibility
 C++ is very strict with regard to type compatibility as compared to
C.
 For instance, C++ defines int, short int. and long int as three
different types.
 They must be cast when their values are assigned to one another.
 Similarly, unsigned char, char, and signed char are considered as
different types, although each of these has a size of one byte.
 In C++, the types of values must be the same for complete
compatibility, or else, a cast must be applied.
 These restrictions in C++ are necessary in order to support function
overloading where two functions with the same name are
distinguished using the type of function arguments.
 Another notable difference is the way char constants are stored. In C,
they are stored as ints, and therefore,
sizeof (' x' )
is equivalent to
sizeof (int) in C.

In C++, however, char is not promoted to the size of int and therefore
sizeof( ' x ' )
equals
sizeof(char)

Type Casting
Type casting refers to the conversion of one data type to another in a program.
Typecasting can be done in two ways:
1. Implicit conversion or Implicit Type Casting
2. Explicit Type Conversion or Explicit Type Casting.
 Implicit Type Casting or Implicit Type Conversion
o It is known as the automatic type casting.
o It automatically converted from one data type to another without any external
intervention such as programmer or user. It means the compiler automatically converts
one data type to another.
o All data type is automatically upgraded to the largest type without losing any
information.
o It can only apply in a program if both variables are compatible with each other.
char - short int -> int -> unsigned int -> long int -> float -> double -> long double, etc.
int num = 5;
float x;
x = num;
output : x = 5.0
 Explicit Type Casting or Explicit Type Conversion
o It is also known as the manual type casting in a program.
o It is manually cast by the programmer or user to change from one data type to another
type in a program. It means a user can easily cast one data to another according to the
requirement in a program.
o It does not require checking the compatibility of the variables.
o In this casting, we can upgrade or downgrade the data type of one variable to another
in a program.
o It uses the cast () operator to change the type of a variable.
Syntax of the explicit type casting
1. (type) expression;
type: It represents the user-defined data that converts the given expression.
expression: It represents the constant value, variable, or an expression whose data type is
converted.
For example, we have a floating pointing number is 4.534, and to convert an integer value,
the statement as:
int num;
num = (int) 4.534; // cast into int data type
cout << num;

Declaration of Variables
 We know that, in C, all variables must be declared before they are
used in executable statements.
 C++ allows the declaration of a variable anywhere in the scope.
 This means that a variable can be declared right at the place of its
first use.
 This makes the program much easier to write and reduces the
errors that may be caused by having to scan back and forth.
 It also makes the program easier to understand because the variables
are declared in the context of their use.
 The example below illustrates this point.

int main()
{
float x;
float sum = 0;
for (i = 0; i <; i++)
{
cin >> x;
sum = sum + x;
}
float average;
average = sum/ ( i-1);
cout << average;
return 0;
}
The only disadvantage of this style of declaration is that we cannot see all the variables
used in scope.

Dynamic Initialization of Variables


C++, however, permits initialization of the variables at run time.
This is referred to as dynamic initialization. In C++, a variable can be initialized at
run time using expressions at the place of declaration.
The following two statements in the example of the previous section

f l o a t average; // declare where it is necessary


average = sum / i;
can be combined into a single statement:

float average = sum/i; // initialize dynamically at run time


Dynamic initialization is extensively used in object-oriented programming. We
can create exactly the type of object needed, using information that is known
only at the run time.

Reference Variables
 C++ introduces a new kind of variable known as the reference variable.
 A reference variable provides an alias (alternative name) for a previously
defined variable.
 For example, if we make the variable sum a reference to the variable
total, then sum and total can be used interchangeably to represent that
variable.
 A reference variable is created as follows:

data-type & reference-name = variable-name


float total = 100; float & sum = total;
 total is a float type variable that has already been declared;
 sum is the alternative name declared to represent the variable total.
 Both the variables refer to the same data object int the memory.
 Now, the statements
cout << total; and cout « sum;

 print the value 100. The statement total = total + 10; will
change the value of both total and sum to 110.

Operators in C + +
C++ has a rich set of
operators.
All C operators are valid in C++ also. In addition, C++ introduces some new
operators.
We have already seen two such operators, namely, the insertion operator << and
the extraction operator >>.
Other new operators are:

:: Scope resolution operator


::* Pointer-to-member declarator
->* Pointer-to-member operator
.* Pointer-to-member operator
Delete Memory release operator
Endl Line feed operator
New Memory allocation operator
Setw Field width operator

Scope Resolution Operator

 In C, the global version of a variable cannot be accessed from within the


inner block.
 C++ resolves this problem by introducing a new operator :: called the
scope resolution operator.
 This can be used to uncover a hidden variable. It takes the following form:
:: variable-name
 This operator allows access to the global version of a variable.
For example,
::count
 means the global version of the variable count (and not the local
variable count declared in that block).
 Following Program illustrates this feature.
The output of Program would be:
We are in inner block k = 20 M = 30
::m = 10
We are in outer block m =20 ::m = 10
 In the above program, the variable m is declared at three places, namely,
outside the main() function, inside the mainO function and inside the
inner block.
 It is to be noted ::m will always refer to the global m. In the inner
block ::m refers to the value 10 and not 20.
 A major application of the scope resolution operator is in the classes
to identify the class to which a member function belongs.
Member Dereferencing Operators
C++ permits us to define a class containing various types of data and
function as members.
C++ also permits us to access the class members through pointers.
In order to achieve this, C++ provides a set of three pointer-to- member
operators. Following are these Member dereferencing operators
Operator Function
:* To declare a pointer to a member of a class
* To access a member using object name and a pointer to that member
—>* To access a member using a pointer to the object and a pointer to that
member
Memory Management Operators
 We use dynamic allocation techniques when it is not known in advance
how much of memory space is needed.
 Although C++ supports these functions, it also defines two unary
operators new and delete that perform the task allocating and freeing
the memory in a better and easier way.
 Since these operators manipulate memory on the free store, they are also
known as free store operators.
 An object can be created by using new and destroyed by using delete,
as and when required.
 A data object created inside a block with new, will remain in existence
until it is explicitly destroyed by using delete.
 The new operator can he used to create objects of any type.
 It takes the following general form
Pointer-variable = new data-type
 Here, pointer-variable is a pointer of type data-type.
 The new operator allocates sufficient memory to hold a data object of type
data-type and returns the address of the object.
 The data-type may be any valid data type.
 The pointer-variable holds the address of the memory space allocated.
Examples:
int *p = new int; float *q = new float;

 We can also initialize the memory using the new operator.


 This is done as follows:
pointer-variable = new data-type(value)
Here, value specifies the initial value. Examples
int *p = new int (25);
float *q = new float(7.510);
 As mentioned earlier, new can be used to create a memory space for
any data- type including user-defined types such as arrays, structures
and classes.
 The general form for a one-dimensional array is:
pointer- variable = new data-type[size];
For example, the statement
int *p = new int [10];
 creates a memory space for an array of 10 integers. p[0] will refer to the
first element, p[1] to the second element, and so on.
 When creating multi-dimensional arrays with new, all the array sizes
must be supplied.

array_ptr = new int[3] [5] [4]; // legal


array_ptr = new int[m][5][4]; // legal
array_ptr = new int[ 3][ 5 ][ ]; // illegal
array_ptr = new int[ ] [5][4]; // Illegal

 The first dimension may be a variable whose value is supplied at


runtime.
 All other must be constants.
 When a data object is no longer needed, it is destroyed to release the
memory space for reuse.
 The general form of its use is:
delete pointer-variable;
 The pointer-variable is the pointer that points to a data object created with
new.
 Examples:
delete p;
delete q;
 If we want to free a dynamically allocated array, we must use the
following form of delete:
delete [size] pointer-variable;
 The size specifies the number of elements in the array to be freed. The
problem with this form is that the programmer should remember the size
of the array.
 Recent versions of C++ do not require the size to be specified. For example
delete [ ]p;
Will delete the entire array pointed to by p
The new operator offers following advantages over the function malloc

 It automatically computes the size of the data object. We need not use the
operatorsizeof.
 It automatically returns the correct pointer type, so that there is no need to
use a type cast
 It is possible to initialize the object while creating the memory
space.
 Like any other operator, new and delete can be overloaded.
Manipulators
 Manipulators are operators that are used to format the data display.
 The most commonly used manipulators are endl a nd setw.
 The endl manipulators when used in an output statement, causes a linefeed
to be inserted.
 It has the same effect as using the new line character "\n". For example,
the statement
cout << “m = “ << m << endl<< “n = “ << n << endl
<< “p = “ << p << endl;
 would cause three line of output for each variable.
 If we assume the values of the variables as 2597, 14 and 175 respectively,
the output will appear as follows.
m = 2597
n = 14
p = 175
 Here, the numbers are right-justified.
 This form of output is possible only if we can specify a common field
width for all the numbers and force them to be printed right-justified.
 The setw manipulator does this job. It is used as follows:
cout « “sum = “;
cout « setw(5) « sum « endl ;
 The manipulator setw(5) specifies a field width 5 for printing the value
of the variable sum.
 This value is right -justified within the field as shown below:

sum = 345
Program illustrates the use of endl and setw.
Control Structure
Introduction:
 C++ is a programming language from a high level that is widely used for creating
applications and software.
 One of the most important concepts in C++ programming is Flow Control, which
refers to the ability to direct the flow of a program based on specific conditions.
 This allows developers to control how their programs execute and can help to make
them more efficient and effective.
the following threecontrol structures:

 Sequence structure (straight line)


 Selection structure (branching)
 Loop structure (iteration or repetition)

Conditional Statements:
 Conditional Statements are used in C++ to run a certain piece of program only if a
specific condition is met.
 There are generally three types of conditional statements in C++: if, if-else,
and switch.
if Statement:
 The if statement is the simplest of the three and is used to run a certain piece of code
only if a certain condition is true.
Syntax:
if (expression is true)
{
action1;
}
action2;
action3;
For example:
int x = 5;
if (x == 5) {
std::cout << "x is 5" << std::endl;
}
 In this example, the block of code inside the curly braces will only be executed if the
condition inside the parentheses is true.
if-else Statement:
 The if-else statement is used when we want to execute some code only if some
condition exists.
 If the given condition is true then code will be executed otherwise else statement will
be used to run other part of the code.
Syntax:
if (expression is true)
{
action1;
}
else
{
action2;
}
action3;
For example:

int x = 5;
if (x == 5) {
std::cout << "x is 5" << std::endl;
} else {
std::cout << "x is not 5" << std::endl;
}
 In this example, if the condition inside the parentheses is true, the first block of code
will be executed.
 Otherwise, the second block of code will be executed.

switch Statement:
The switch statement is used to execute different blocks of code based on the value of a
variable.
Syntax:

switch (variable) {
case value1:
// code to execute if the variable is equal to value1
break;
case value2:
// code to execute if the variable is equal to value2
break;
// add more cases as needed
default:
// code to execute if the variable does not match any case
}
Example:

int x = 2;
switch (x) {
case 1:
std::cout << "x is 1" << std::endl;
break;
case 2:
std::cout << "x is 2" << std::endl;
break;
default:
std::cout << "x is not 1 or 2" << std::endl;
break;
}
 In this example, the switch statement will execute the block of code associated with
the value of x.
 If x is 1, the first block of code will be executed.
 If x is 2, the second block of code will be executed.
 If x is any other value, the default block of code will be executed.

Loops:
 Loops are used in C++ to execute a block of code multiple times, either until a certain
condition is met or for a specific number of times.
 There are generally three types of loops in C++: while, do-while, and for.
While Loop:
 The while loop is used to execute when we want to run some code for until some
specific condition matches.
 This is also a loop structure, but is an entry-controlled one.

Syntax:
while(condition is true)
{
actionl;
}
action2;
Example:
int x = 0;
while (x < 5) {
std::cout << x << std::endl;
x++; }
 In this example, the while loop will continue to execute the block of code inside the
curly braces as long as x is less than 5.
 Each time the loop executes, the value of x will be incremented by 1.

do-while Loop:
 The do-while loop is the same as the while loop, but the condition is checked after
the first iteration of the loop.
 The do-while is an exit-controlled loop.

Syntax:
do
{
actionl ;
}
while(condition is true);
action2;
Example:
AD
int x = 0;
do {
std::cout << x << std::endl;
x++;
} while (x < 5);
 In this example, the do-while loop will execute the block of code inside the curly
brackets, and then it will check the condition.
 So it will be executed a minimum of one time.
for Loop:
 The for loop allows a program to execute a piece of program a fixed number of
times.
Syntax:
for (initialization; condition; increment/decrement)
{
// code to execute repeatedly
}
Here is an example that uses the for loop to print the numbers from 1 to 10:
for (int i = 1; i <= 10; i++)
{
cout << i << " ";
}

You might also like