0% found this document useful (0 votes)
24 views76 pages

OOP (C++) Unit1

Uploaded by

Prince Badampudi
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 views76 pages

OOP (C++) Unit1

Uploaded by

Prince Badampudi
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/ 76

Rajiv Gandhi University of Knowledge Technologies-AP.

SEM2-E1-ECE
Object Oriented Programming with C++
Unit-1:
Review of C: strings, arrays,pointers, Programming in C++, Build and
execute a C program in C++, C++ as better C: Procedural Execution of C

About C
C Programming Language
The C Language is developed by Dennis Ritchie for creating system applications that
directly interact with the hardware devices such as drivers, kernels, etc.

C programming is considered as the base for other programming languages, that is why
it is known as mother language.

It can be defined by the following ways:

1. Mother language

2. System programming language

3. Procedure-oriented programming language

4. Structured programming language

5. Mid-level programming language

1) C as a mother language
C language is considered as the mother language of all the modern programming
languages because most of the compilers, JVMs, Kernels, etc. are written in C
language, and most of the programming languages follow C syntax, for example,
C++, Java, C#, etc.
It provides the core concepts like the array, strings, functions, file handling, etc. that
are being used in many languages like C++, Java, C#, etc.

2) C as a system programming language


A system programming language is used to create system software. C language is a
system programming language because it can be used to do low-level
programming (for example driver and kernel). It is generally used to create
hardware devices, OS, drivers, kernels, etc. For example, Linux kernel is written in C.

It can't be used for internet programming like Java, .Net, PHP, etc.

3) C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural
language specifies a series of steps for the program to solve the problem.

A procedural language breaks the program into functions, data structures, etc.

C is a procedural language. In C, variables and function prototypes must be declared


before being used.

4) C as a structured programming language


A structured programming language is a subset of the procedural language. Structure
means to break a program into parts or blocks so that it may be easy to
understand.

In the C language, we break the program into parts using functions. It makes the
program easier to understand and modify.

5) C as a mid-level programming language


C is considered as a middle-level language because it supports the feature of both
low-level and high-level languages. C language program is converted into assembly
code, it supports pointer arithmetic (low-level), but it is machine independent (a feature
of high-level).

A Low-level language is specific to one machine, i.e., machine dependent. It is


machine dependent, fast to run. But it is not easy to understand.

A High-Level language is not specific to one machine, i.e., machine independent. It is


easy to understand.
C Program
In this tutorial, all C programs are given with C compiler so that you can quickly change
the C program code.

File: main.c

Output:

Hello C Programming

A detailed description of above program is given in next chapters.

History of C Language
History of C language is interesting to know. Here we are going to discuss
a brief history of the c language.

C programming language was developed in 1972 by Dennis Ritchie at bell


laboratories of AT&T (American Telephone & Telegraph), located in the
U.S.A.

Dennis Ritchie is known as the founder of the c language.

It was developed to overcome the problems of previous languages such as B, BCPL,


etc.

Initially, C language was developed to be used in UNIX operating system. It inherits


many features of previous languages such as B and BCPL.
Features of C Language

C is the widely used language. It provides many features that are given below.

1. Simple

2. Machine Independent or Portable

3. Mid-level programming language

4. structured programming language

5. Rich Library

6. Memory Management

7. Fast Speed

8. Pointers

9. Recursion

10. Extensible
1) Simple
C is a simple language in the sense that it provides a structured approach (to break
the problem into parts), the rich set of library functions, data types, etc.

2) Machine Independent or Portable


Unlike assembly language, c programs can be executed on different machines with
some machine specific changes. Therefore, C is a machine independent language.

3) Mid-level programming language


Although, C is intended to do low-level programming. It is used to develop system
applications such as kernel, driver, etc. It also supports the features of a high-level
language. That is why it is known as mid-level language.

4) Structured programming language


C is a structured programming language in the sense that we can break the program
into parts using functions. So, it is easy to understand and modify. Functions also
provide code reusability.

5) Rich Library
C provides a lot of inbuilt functions that make the development fast.

6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free
the allocated memory at any time by calling the free() function.

7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt
functions and hence the lesser overhead.

8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array, etc.

9) Recursion
In C, we can call the function within the function. It provides code reusability for
every function. Recursion enables us to use the approach of backtracking.
10) Extensible
C language is extensible because it can easily adopt new features.

C Array
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which
can store the primitive type of data such as int, char, double, float, etc. It also has the
capability to store the collection of derived data types, such as pointers, structure, etc.
The array is the simplest data structure where each data element can be randomly
accessed by using its index number.

C array is beneficial if you have to store similar elements. For example, if we want to
store the marks of a student in 6 subjects, then we don't need to define different
variables for the marks in the different subject. Instead of that, we can define an array
which can store the marks in each subject at the contiguous memory locations.

By using the array, we can access the elements easily. Only a few lines of code are
required to access the elements of the array.

Properties of Array
The array contains the following properties.

o Each element of an array is of same data type and carries the same size, i.e., int
= 4 bytes.

o Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.

o Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size of
the data element.

Advantage of C Array
1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array
easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code
only.

4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we
can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we
will learn later.

Declaration of C Array
We can declare an array in the c language in the following way.

1. data_type array_name[array_size];

Now, let us see the example to declare the array.

int marks[5];

Here, int is the data_type, marks are the array_name, and 5 is the array_size.

Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize
each element of the array by using the index. Consider the following example.

marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
C array example

Output
C Array: Declaration with Initialization
We can initialize the c array at the time of declaration. Let's see the code.

int marks[5]={20,30,40,50,60};

In such case, there is no requirement to define. So


the sizealso be written as the
it may
following code.

int marks[]={20,30,40,50,60};

Let's see the C program to declare and initialize the array in C.


C Array Example: Sorting an array
In the following program, we are using bubble sort method to sort the array in
ascending order.
C Strings
The string can be defined as the one-dimensional array of characters terminated by a
null ('\0'). The character array or the string is used to manipulate text such as word or
sentences. Each character in the array occupies one byte of memory, and the last
character must always be 0. The termination character ('\0') is important in a string
since it is the only way to identify where the string ends. When we define a string as
char s[10], the character s[10] is implicitly initialized with the null in the memory.

There are two ways to declare a string in c language.

1. By char array

2. By string literal

Let's see the example of declaring string by char array in C language.

1. char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

As we know, array index starts from 0, so it will be represented as in the figure given
below.

While declaring string, size is not mandatory. So we can write the above code as given
below:

In such case, '\0' will be appended at the end of the string by the compiler.
Difference between char array and string literal
There are two main differences between char array and literal.

o We need to add the null character '\0' at the end of the array by ourself
whereas, it is appended internally by the compiler in the case of the character
array.

o The string literal cannot be reassigned to another set of characters whereas, we


can reassign the characters of the array.

String Example in C
Let's see a simple example where a string is declared and being printed. The
'%s' is used as a format specifier for the string in c language.
Traversing String
Traversing the string is one of the most important aspects in any of the programming
languages. We may need to manipulate a very large text which can be done by
traversing the text. Traversing string is somewhat different from the traversing an
integer array. We need to know the length of the array to traverse an integer array,
whereas we may use the null character in the case of string to identify the end the
string and terminate the loop.

Hence, there are two ways to traverse a string.

o By using the length of string

o By using the null character.

Let's discuss each one of them.

Using the length of string


Let's see an example of counting the number of vowels in a string.
}

Output

Using the null character


Let's see the same example of counting the number of vowels by using the
null character.
Output

Accepting string as the input


Till now, we have used scanf to accept the input from the user. However, it can also be us
the case of strings but with a different scenario. Consider the below code which stores the
string while space is encountered.
It is clear from the output that, the above code will not work for space separated
strings. To make this code working for the space separated strings, the minor changed
required in the scanf function, i.e., instead of writing scanf("%s",s), we must write:
scanf("%[^\n]s",s) which instructs the compiler to store the string s while the new line
(\n) is encountered. Let's consider the following example to store the space-separated
strings.
Some important points
However, there are the following points which must be noticed while entering the
strings by using scanf.

o The compiler doesn't perform bounds checking on the character array. Hence,
there can be a case where the length of the string can exceed the dimension of
the character array which may always overwrite some important data.

o Instead of using scanf, we may use gets() which is an inbuilt function defined in
a header file string.h. The gets() is capable of receiving only one string at a time.
Pointers with strings
We have used pointers with the array, functions, and primitive data types so far. However
pointers can be used to point to the strings. There are various advantages of using pointer
point strings. Let us consider the following example to access the string via the pointer.
As we know that string is an array of characters, the pointers can be used in the same
way they were used with arrays. In the above example, p is declared as a pointer to the
array of characters s. P affects similar to s since s is the base address of the string and
treated as a pointer internally. However, we can not change the content of s or copy
the content of s into another string directly. For this purpose, we need to use the
pointers to store the strings. In the following example, we have shown the use of
pointers to copy the content of a string into another.
Once a string is defined, it cannot be reassigned to another set of characters. However, us
pointers, we can assign the set of characters to the string. Consider the following example
C Pointers
The pointer in C language is a variable which stores the address
of another variable. This variable can be of type int, char, array,
function, or any other pointer. The size of the pointer depends on
the architecture. However, in 32-bit architecture the size of a
pointer is 2 byte.

Consider the following example to define a pointer which stores


the address of an integer.
Let's see the pointer example as explained for the above figure.
Usage of pointer
There are many applications of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc()


functions where the pointer is used.

2) Arrays, Functions, and Structures

Pointers in c language are widely used in arrays, functions, and structures. It reduces
the code and improves the performance.

Address Of (&) Operator


The address of operator '&' returns the address of a variable. But, we need to use %u to d
the address of a variable.
NULL Pointer
A pointer that is not assigned any value but NULL is known as the NULL pointer. If you
don't have any address to be specified in the pointer at the time of declaration, you can
assign NULL value. It will provide a better approach.

Pointer Program to swap two numbers without using


the 3rd variable.
Output

Reading complex pointers


There are several things which must be taken into the consideration while reading the
complex pointers in C. Lets see the precedence and associativity of the operators which
are used regarding pointers.
C Functions
In c, we can divide a large program into the basic building blocks known as function.
The function contains the set of programming statements enclosed by {}. A function
can be called multiple times to provide reusability and modularity to the C program. In
other words, we can say that the collection of functions creates a program. The function
is also known as procedureor subroutinein other programming languages.

Advantage of functions in C
There are the following advantages of C functions.

o By using functions, we can avoid rewriting same logic/code again and again in a
program.

o We can call C functions any number of times in a program and from any place in
a program.

o We can track a large C program easily when it is divided into multiple functions.

o Reusability is the main achievement of C functions.

o However, Function calling is always a overhead in a C program.

Function Aspects
There are three aspects of a C function.

o Function declaration A function must be declared globally in a c program to


tell the compiler about the function name, function parameters, and return type.

o Function call Function can be called from anywhere in the program. The
parameter list must not differ in function calling and function declaration. We
must pass the same number of functions as it is declared in the function
declaration.

o Function definition It contains the actual statements which are to be executed.


It is the most important aspect to which the control comes when the function is
called. Here, we must notice that only one value can be returned from the
function.
SN C function Syntax
aspects

1 Function return_type function_name (argument


declaration list);

2 Function call function_name (argument_list)

3 Function return_type function_name (argument list)


definition {function body;}

The syntax of creating function in c language is given below:


About C++
C++ is an object-oriented programming language. It is an extension to C programming.

Our C++ tutorial includes all topics of C++ such as first example, control statements,
objects and classes, inheritance, constructor, destructor, this, static, polymorphism,
abstraction, abstract class, interface, namespace, encapsulation, arrays, strings,
exception handling, File IO, etc.

What is C++
C++ is a general purpose, case-sensitive, free-form programming language that
supports object-oriented, procedural and generic programming.

C++ is a middle-level language, as it encapsulates both high and low level language
features.

Object-Oriented Programming (OOPs)


C++ supports the object-oriented programming, the four major pillar of object-oriented
programming (OOPs) used in C++ are:

1. Inheritance

2. Polymorphism

3. Encapsulation

4. Abstraction

C++ Standard Libraries


Standard C++ programming is divided into three important parts:

o The core library includes the data types, variables and literals, etc.

o The standard library includes the set of functions manipulating strings, files, etc.

o The Standard Template Library (STL) includes the set of methods manipulating a
data structure.
Usage of C++
By the help of C++ programming language, we can develop different types of secured and
robust applications:

o Window application

o Client-Server application

o Device drivers

o Embedded firmware etc

C++ Program
In this tutorial, all C++ programs are given with C++ compiler so that you can easily chan
C++ program code.

File: main.cpp

C is a structural or procedural oriented programming language which is machine-


independent and extensively used in various applications.

C is the basic programming language that can be used to develop from the operating
systems (like Windows) to complex programs like Oracle database, Git, Python
interpreter, and many more. C programming language can be called a god's
programming language as it forms the base for other programming languages. If we
know the C language, then we can easily learn other programming languages. C
language was developed by the great computer scientist Dennis Ritchie at the Bell
Laboratories. It contains some additional features that make it unique from other
programming languages.

What is C++?
C++ is a special-purpose programming language developed by Bjarne Stroustrup at
Bell Labs circa 1980. C++ language is very similar to C language, and it is so
compatible with C that it can run 99% of C programs without changing any source of
code though C++ is an object-oriented programming language, so it is safer and well-
structured programming language than C.

Let's understand the differences between C and C++.

The following are the differences between C and C++:

ADVERTISEMENT

o Definition
C is a structural programming language, and it does not support classes and
objects, while C++ is an object-oriented programming language that supports
the concept of classes and objects.

o Type of programming language


C supports the structural programming language where the code is checked line
by line, while C++ is an object-oriented programming language that supports
the concept of classes and objects.
o Developer of the language
Dennis Ritchie developed C language at Bell Laboratories while Bjarne Stroustrup
developed the C++ language at Bell Labs circa 1980.

o Subset
C++ is a superset of C programming language. C++ can run 99% of C code but
C language cannot run C++ code.

o Type of approach
C follows the top-down approach, while C++ follows the bottom-up approach.
The top-down approach breaks the main modules into tasks; these tasks are
broken into sub-tasks, and so on. The bottom-down approach develops the lower
level modules first and then the next level modules.

o Security
In C, the data can be easily manipulated by the outsiders as it does not support
the encapsulation and information hiding while C++ is a very secure language,
i.e., no outsiders can manipulate its data as it supports both encapsulation and
data hiding. In C language, functions and data are the free entities, and in C++
language, all the functions and data are encapsulated in the form of objects.

o Function Overloading
Function overloading is a feature that allows you to have more than one function
with the same name but varies in the parameters. C does not support the
function overloading, while C++ supports the function overloading.

o Function Overriding
Function overriding is a feature that provides the specific implementation to the
function, which is already defined in the base class. C does not support the
function overriding, while C++ supports the function overriding.

o Reference variables
C does not support the reference variables, while C++ supports the reference
variables.

o Keywords
C contains 32 keywords, and C++ supports 52 keywords.

o Namespace feature
A namespace is a feature that groups the entities like classes, objects, and
functions under some specific name. C does not contain the namespace feature,
while C++ supports the namespace feature that avoids the name collisions.

o Exception handling
C does not provide direct support to the exception handling; it needs to use
functions that support exception handling. C++ provides direct support to
exception handling by using a try-catch block.

o Input/Output functions
In C, scanf and printf functions are used for input and output operations,
respectively, while in C++, cin and cout are used for input and output
operations, respectively.

o Memory allocation and de-allocation


C supports calloc() and malloc() functions for the memory allocation, and free()
function for the memory de-allocation. C++ supports a new operator for the
memory allocation and delete operator for the memory de-allocation.

o Inheritance
Inheritance is a feature that allows the child class to reuse the properties of the
parent class. C language does not support the inheritance while C++ supports
the inheritance.

o Header file
C program uses <stdio.h> header file while C++ program
uses <iostream.h> header file.

Let's summarize the above differences in a tabular form.

No. C C++

1) C follows the procedural C++ is multi-paradigm. It supports


style programming. both procedural and object oriented.

2) Data is less secured in C. In C++, you can use modifiers for class
members to make it inaccessible for
outside users.

3) C follows the top-down C++ follows the bottom-up approach.


approach.

4) C does not support function C++ supports function overloading.


overloading.

5) In C, you can't use functions in In C++, you can use functions in


structure. structure.

6) C does not support reference C++ supports reference variables.


variables.

7) In C, scanf() and printf() are C++ mainly uses stream cin and
mainly used for input/output. cout to perform input and output
operations.

8) Operator overloading is not Operator overloading is possible in C++.


possible in C.

9) C programs are divided C++ programs are divided


into procedures and into functions and classes.
modules

10) C does not provide the feature C++ supports the feature of namespace.
of namespace.

11) Exception handling is not easy C++ provides exception handling using
in C. It has to perform using Try and Catch block.
other functions.

12) C does not support the C++ supports inheritance.


inheritance.
C++ history
History of C++ language is interesting to know. Here we are going to discuss brief
history of C++ language.

C++ programming language was developed in 1980 by Bjarne Stroustrup at bell


laboratories of AT&T (American Telephone & Telegraph), located
in U.S.A.

Bjarne Stroustrup is known as the founder of C++


language.

It was develop for adding a feature of OOP (Object Oriented


Programming) in C without significantly changing the C
component.

C++ programming is "relative" (called a superset) of C, it


means any valid C program is also a valid C++ program.

C++ Features
C++ is object oriented programming language. It provides a lot of features that are
given below.
1. Simple

2. Machine Independent or Portable

3. Mid-level programming language

4. Structured programming language

5. Rich Library

6. Memory Management

7. Fast Speed

8. Pointers

9. Recursion

10. Extensible

11. Object Oriented

12. Compiler based

1) Simple
C++ is a simple language in the sense that it provides structured approach (to break
the problem into parts), rich set of library functions, data types etc.

2) Machine Independent or Portable


Unlike assembly language, c programs can be executed in many machines with little bit
or no change. But it is not platform-independent.

3) Mid-level programming language

C++ is also used to do low level programming. It is used to develop system


applications such as kernel, driver etc. It also supports the feature of high level
language. That is why it is known as mid-level language.

4) Structured programming language


C++ is a structured programming language in the sense that we can break the program
into parts using functions. So, it is easy to understand and modify.
5) Rich Library
C++ provides a lot of inbuilt functions that makes the development fast.

6) Memory Management
It supports the feature of dynamic memory allocation. In C++ language, we can free
the allocated memory at any time by calling the free() function.

7) Speed
The compilation and execution time of C++ language is fast.

8) Pointer
C++ provides the feature of pointers. We can directly interact with the memory by
using the pointers. We can use pointers for memory, structures, functions, array etc.

9) Recursion
In C++, we can call the function within the function. It provides code reusability for
every function.

10) Extensible
C++ language is extensible because it can easily adopt new features.

11) Object Oriented


C++ is object oriented programming language. OOPs makes development and
maintenance easier where as in Procedure-oriented programming language it is not
easy to manage if code grows as project size grows.

12) Compiler based


C++ is a compiler based programming language, it means without compilation no C++
program can be executed. First we need to compile our program using compiler and
then we can execute our program.
C++ Program, Input/Output,(cin,cout,endl),
Variables, Keywords,Data Types, Operators

C++ Program
Before starting the abcd of C++ language, you need to learn how to write, compile and
run the first C++ program.

To write the first C++ program, open the C++ console and write the following code:

1. #include <iostream.h>
2. #include<conio.h>
3. void main() {
4. clrscr();
5. cout << "Welcome to C++ Programming.";
6. getch();
7. }

#include<iostream.h> includes the standard input output library functions. It


provides cin and cout methods for reading from input and writing to output respectively.

#include <conio.h> includes the console input output library functions. The getch()
function is defined in conio.h file.

void main() The main() function is the entry point of every program in C++
language. The void keyword specifies that it returns no value.

cout << "Welcome to C++ Programming." is used to print the data "Welcome to C++
Programming." on the console.

getch() The getch() function asks for a single character. Until you press any key, it blocks the
screen.
C++ Basic Input/Output

C++ I/O operation is using the stream concept. Stream is the sequence of bytes or flow
of data. It makes the performance fast.

If bytes flow from main memory to device like printer, display screen, or a network
connection, etc, this is called as output operation.

If bytes flow from device like printer, display screen, or a network connection, etc to
main memory, this is called as input operation.

I/O Library Header Files


Let us see the common header files used in C++ programming are:

Header Function and Description


File

<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard output
stream, standard input stream and standard error stream, respectively.

<iomanip> It is used to declare services useful for performing formatted I/O, such as setprecision and
setw.

<fstream> It is used to declare services for user-controlled file processing.


Standard output stream (cout)
The cout is a predefined object of ostream class. It is connected with the standard
output device, which is usually a display screen. The cout is used in conjunction with
stream insertion operator (<<) to display the output on a console

Let's see the simple example of standard output stream (cout):

1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. char ary[] = "Welcome to C++ tutorial";
5. cout << "Value of ary is: " << ary << endl; // similar like printf() in C
6. }

Output:

Value of ary is: Welcome to C++ tutorial

Standard input stream (cin)


The cin is a predefined object of istream class. It is connected with the standard input
device, which is usually a keyboard. The cin is used in conjunction with stream
extraction operator (>>) to read the input from a console.

Let's see the simple example of standard input stream (cin):

1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. int age;
5. cout << "Enter your age: ";
6. cin >> age; //similar like scanf() in C
7. cout << "Your age is: " << age << endl;
8. }

Output:
Enter your age: 22
Your age is: 22

Standard end line (endl)


The endl is a predefined object of ostream class. It is used to insert a new line
characters and flushes the stream.

Let's see the simple example of standard end line (endl):

1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. cout << "C++ Tutorial";
5. cout << " Javatpoint"<<endl; // it is a new line similar like \n in C
6. cout << "End of line"<<endl;
7. }

Output:

C++ Tutorial Javatpoint


End of line

C++ Variable
A variable is a name of memory location. It is used to store data. Its value can be
changed and it can be reused many times.

It is a way to represent memory location through symbol so that it can be easily


identified.

Let's see the syntax to declare a variable:

1. type variable_list; // here type indicate datatype or type of data

The example of declaring variable is given below:

1. int x;
2. float y;
3. char z;

Here, x, y, z are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

1. int x=5,b=10; //declaring 2 variable of integer type


2. float f=30.8;
3. char c='A';

4. char ary[] = "Welcome to C++ tutorial"; // Declaring a string called array of characters

Rules for defining variables


A variable can have alphabets, digits and underscore.

A variable name can start with alphabet and underscore only. It can't start with digit.

No white space is allowed within variable name.

A variable name must not be any reserved word or keyword e.g. char, float etc.

Valid variable names:

1. int a;
2. int _ab;
3. int a30;

Invalid variable names:

1. int 4;
2. int x y;
3. int double;

C++ Data Types


A data type specifies the type of data that a variable can store such as integer, floating, character
etc.
There are 4 types of data types in C++ language.

Types Data Types

Basic Data Type int, char, float, double, etc

Derived Data Type array, pointer, etc

Enumeration Data Type Enum

User Defined Data Type Structure

Basic Data Types


The basic data types are integer-based and floating-point based. C++ language supports both
signed and unsigned literals.

The memory size of basic data types may change according to 32 or 64 bit operating system.

Let's see the basic data types. It size is given according to 32 bit OS.
Data Types Memory Size Range

Char 1 byte -128 to 127

signed char 1 byte -128 to 127

unsigned char 1 byte 0 to 127

short 2 byte -32,768 to 32,767

signed short 2 byte -32,768 to 32,767

unsigned short 2 byte 0 to 32,767

int 2 byte -32,768 to 32,767

signed int 2 byte -32,768 to 32,767

unsigned int 2 byte 0 to 32,767

short int 2 byte -32,768 to 32,767

signed short int 2 byte -32,768 to 32,767

unsigned short int 2 byte 0 to 32,767

long int 4 byte

signed long int 4 byte


unsigned long int 4 byte

float 4 byte

double 8 byte

long double 10 byte

C++ Keywords
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A list of 32
Keywords in C++ Language which are also available in C language are given below.

auto break case char const continue Default do

double else enum extern float for Goto if

int long register return short signed Sizeof static

struct switch typedef union unsigned void Volatile while

A list of 30 Keywords in C++ Language which are not available in C language are given below.

asm dynamic_cast namespace reinterpret_cast bool

explicit new static_cast false catch

operator template friend private class

this inline public throw const_cast

delete mutable protected true try

typeid typename using virtual wchar_t


C++ Operators
An operator is simply a symbol that is used to perform operations. There can be many
types of operations like arithmetic, logical, bitwise etc.

There are following types of operators to perform different types of operations in C


language.

o Arithmetic Operators

o Relational Operators

o Logical Operators

o Bitwise Operators

o Assignment Operator

o Unary operator

o Ternary or Conditional Operator

o Misc Operator
Precedence of Operators in C++
The precedence of operator species that which operator will be evaluated first and next.
The associativity specifies the operators direction to be evaluated, it may be left to right
or right to left.

Let's understand the precedence by the example given below:

1. int data=5+10*10;

The "data" variable will contain 105 because * (multiplicative operator) is evaluated
before + (additive operator).

The precedence and associativity of C++ operators is given below:

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Right to left

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == !=/td> Right to left

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Right to left

Logical AND && Left to right

Logical OR || Left to right


Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right


C++ Identifiers
C++ identifiers in a program are used to refer to the name of the variables, functions, arrays, or other
user-defined data types created by the programmer. They are the basic requirement of any
language. Every language has its own rules for naming the identifiers.

In short, we can say that the C++ identifiers represent the essential elements in a program which are
given below:

o Constants

o Variables

o Functions

o Labels

o Defined data types

Some naming rules are common in both C and C++. They are as follows:

o Only alphabetic characters, digits, and underscores are allowed.

o The identifier name cannot start with a digit, i.e., the first letter should be alphabetical. After
the first letter, we can use letters, digits, or underscores.

o In C++, uppercase and lowercase letters are distinct. Therefore, we can say that C++
identifiers are case-sensitive.

o A declared keyword cannot be used as a variable name.

For example, suppose we have two identifiers, named as 'FirstName', and 'Firstname'. Both the
identifiers will be different as the letter 'N' in the first case in uppercase while lowercase in second.
Therefore, it proves that identifiers are case-sensitive.

Valid Identifiers

The following are the examples of valid identifiers are:

Result
Test2
_sum
power
Invalid Identifiers

The following are the examples of invalid identifiers:

Sum-1 // containing special character '-'.


2data // the first letter is a digit.
break // use of a keyword.

Note: Identifiers cannot be used as the keywords. It may not conflict with the keywords, but
it is highly recommended that the keywords should not be used as the identifier name. You
should always use a consistent way to name the identifiers so that your code will be more
readable and maintainable.

The major difference between C and C++ is the limit on the length of the name of the
variable. ANSI C considers only the first 32 characters in a name while ANSI C++
imposes no limit on the length of the name.

Constants are the identifiers that refer to the fixed value, which do not change during
the execution of a program. Both C and C++ support various kinds of literal constants,
and they do have any memory location. For example, 123, 12.34, 037, 0X2, etc. are the
literal constants.

Let's look at a simple example to understand the concept of identifiers.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a;
6. int A;
7. cout<<"Enter the values of 'a' and 'A'";
8. cin>>a;
9. cin>>A;
10. cout<<"\nThe values that you have entered are : "<<a<<" , "<<A;
11. return 0;
12. }
In the above code, we declare two variables 'a' and 'A'. Both the letters are same but
they will behave as different identifiers. As we know that the identifiers are the case-
sensitive so both the identifiers will have different memory locations.

Output

What are the keywords?


Keywords are the reserved words that have a special meaning to the compiler. They are reserved
for a special purpose, which cannot be used as the identifiers. For example, 'for', 'break', 'while', 'if',
'else', etc. are the predefined words where predefined words are those words whose meaning is
already known by the compiler. Whereas, the identifiers are the names which are defined by the
programmer to the program elements such as variables, functions, arrays, objects, classes.

Differences between Identifiers and Keywords

The following is the list of differences between identifiers and keywords:

Identifiers Keywords

Identifiers are the names defined by the programmer to the Keywords are the reserved words whose meaning
basic elements of a program. is known by the compiler.

It is used to identify the name of the variable. It is used to specify the type of entity.

It can consist of letters, digits, and underscore. It contains only letters.

It can use both lowercase and uppercase letters. It uses only lowercase letters.

No special character can be used except the underscore. It cannot contain any special character.
The starting letter of identifiers can be lowercase, It can be started only with the lowercase letter.
uppercase or underscore.

It can be classified as internal and external identifiers. It cannot be further classified.

Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else', 'break', etc.

C++ Expression
C++ expression consists of operators, constants, and variables which are arranged according to the
rules of the language. It can also contain function calls which return values. An expression can
consist of one or more operands, zero or more operators to compute a value. Every expression
produces some value which is assigned to the variable with the help of an assignment operator.

Examples of C++ expression:

1. (a+b) - c
2. (x/y) -z
3. 4a2 - 5b +c
4. (a+b) * (x+y)

An expression can be of following types:


o Constant expressions

o Integral expressions

o Float expressions

o Pointer expressions

o Relational expressions

o Logical expressions

o Bitwise expressions

o Special assignment expressions


If the expression is a combination of the above expressions, such expressions are
known as compound expressions.

Constant expressions
A constant expression is an expression that consists of only constant values. It is an
expression whose value is determined at the compile-time but evaluated at the run-time.
It can be composed of integer, character, floating-point, and enumeration constants.

Constants are used in the following situations:

o It is used in the subscript declarator to describe the array bound.

o It is used after the case keyword in the switch statement.

o It is used as a numeric value in an enum

o It specifies a bit-field width.


o It is used in the pre-processor #if

In the above scenarios, the constant expression can have integer, character, and
enumeration constants. We can use the static and extern keyword with the constants to
define the function-scope.

The following table shows the expression containing constant value:

Expression containing constant Constant value

x = (2/3) * 4 (2/3) * 4

extern int y = 67 67

int z = 43 43

static int a = 56 56

Let's see a simple program containing constant expression:

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x; // variable declaration.
6. x=(3/2) + 2; // constant expression
7. cout<<"Value of x is : "<<x; // displaying the value of x.
8. return 0;
9. }

In the above code, we have first declared the 'x' variable of integer type. After
declaration, we assign the simple constant expression to the 'x' variable.

Output
Value of x is : 3

Integral Expressions
An integer expression is an expression that produces the integer value as output after
performing all the explicit and implicit conversions.

Following are the examples of integral expression:

1. (x * y) -5
2. x + int(9.0)
3. where x and y are the integers.

Let's see a simple example of integral expression:

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x; // variable declaration.
6. int y; // variable declaration
7. int z; // variable declaration
8. cout<<"Enter the values of x and y";
9. cin>>x>>y;
10. z=x+y;
11. cout<<"\n"<<"Value of z is :"<<z; // displaying the value of z.
12. return 0;
13. }
In the above code, we have declared three variables, i.e., x, y, and z. After declaration, we take
the user input for the values of 'x' and 'y'. Then, we add the values of 'x' and 'y' and stores their
result in 'z' variable.

Output

Enter the values of x and y


8
9
Value of z is :17

Let's see another example of integral expression.


1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
6. int x; // variable declaration
7. int y=9; // variable initialization
8. x=y+int(10.0); // integral expression
9. cout<<"Value of x : "<<x; // displaying the value of x.
10. return 0;
11. }

In the above code, we declare two variables, i.e., x and y. We store the value of
expression (y+int(10.0)) in a 'x' variable.

Output

Value of x : 19

Float Expressions
A float expression is an expression that produces floating-point value as output after
performing all the explicit and implicit conversions.

The following are the examples of float expressions:

1. x+y
2. (x/10) + y
3. 34.5
4. x+float(10)

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
6. float x=8.9; // variable initialization
7. float y=5.6; // variable initialization
8. float z; // variable declaration
9. z=x+y;
10. std::cout <<"value of z is :" << z<<std::endl; // displaying the value of z.
11.
12.
13. return 0;
14. }

Output

value of z is :14.5

Let's see another example of float expression.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. float x=6.7; // variable initialization
6. float y; // variable declaration
7. y=x+float(10); // float expression
8. std::cout <<"value of y is :" << y<<std::endl; // displaying the value of y
9. return 0;
10. }

In the above code, we have declared two variables, i.e., x and y. After declaration, we store the
value of expression (x+float(10)) in variable 'y'.

Output

value of y is :16.7

Pointer Expressions
A pointer expression is an expression that produces address value as an output.

The following are the examples of pointer expression:

1. &x
2. ptr
3. ptr++
4. ptr-

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
6. int a[]={1,2,3,4,5}; // array initialization
7. int *ptr; // pointer declaration
8. ptr=a; // assigning base address of array to the pointer ptr
9. ptr=ptr+1; // incrementing the value of pointer
10. std::cout <<"value of second element of an array : " << *ptr<<std::endl;
11. return 0;
12. }

In the above code, we declare the array and a pointer ptr. We assign the base address to the
variable 'ptr'. After assigning the address, we increment the value of pointer 'ptr'. When pointer is
incremented then 'ptr' will be pointing to the second element of the array.

Output

value of second element of an array : 2

Relational Expressions
A relational expression is an expression that produces a value of type bool, which can be either true
or false. It is also known as a boolean expression. When arithmetic expressions are used on both
sides of the relational operator, arithmetic expressions are evaluated first, and then their results are
compared.

The following are the examples of the relational expression:

1. a>b
2. a-b >= x-y
3. a+b>80

Let's understand through an example


1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=45; // variable declaration
6. int b=78; // variable declaration
7. bool y= a>b; // relational expression
8. cout<<"Value of y is :"<<y; // displaying the value of y.
9. return 0;
10. }

In the above code, we have declared two variables, i.e., 'a' and 'b'. After declaration, we have
applied the relational operator between the variables to check whether 'a' is greater than 'b' or not.

Output

Value of y is :0

Let's see another example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=4; // variable declaration
6. int b=5; // variable declaration
7. int x=3; // variable declaration
8. int y=6; // variable declaration
9. cout<<((a+b)>=(x+y)); // relational expression
10. return 0;
11. }

In the above code, we have declared four variables, i.e., 'a', 'b', 'x' and 'y'. Then, we apply the
relational operator (>=) between these variables.

Output

1
Logical Expressions
A logical expression is an expression that combines two or more relational expressions and
produces a bool type value. The logical operators are '&&' and '||' that combines two or more
relational expressions.

The following are some examples of logical expressions:

1. a>b && x>y


2. a>10 || b==5

Let's see a simple example of logical expression.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=2;
6. int b=7;
7. int c=4;
8. cout<<((a>b)||(a>c));
9. return 0;
10. }

Output

Bitwise Expressions
A bitwise expression is an expression which is used to manipulate the data at a bit level. They are
basically used to shift the bits.

For example:

x=3

x>>3 // This statement means that we are shifting the three-bit position to the right.

In the above example, the value of 'x' is 3 and its binary value is 0011. We are shifting the value of 'x'
by three-bit position to the right. Let's understand through the diagrammatic representation.
Let's see a simple example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x=5; // variable declaration
6. std::cout << (x>>1) << std::endl;
7. return 0;
8. }

In the above code, we have declared a variable 'x'. After declaration, we applied the bitwise
operator, i.e., right shift operator to shift one-bit position to right.

Output
2

Let's look at another example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x=7; // variable declaration
6. std::cout << (x<<3) << std::endl;
7. return 0;
8. }

In the above code, we have declared a variable 'x'. After declaration, we applied the left shift
operator to variable 'x' to shift the three-bit position to the left.

Output

56

Special Assignment Expressions


Special assignment expressions are the expressions which can be further classified depending upon
the value assigned to the variable.

o Chained Assignment

Chained assignment expression is an expression in which the same value is assigned to more than
one variable by using single statement.

For example:

1. a=b=20
2. or
3. (a=b) = 20

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4.
5. int a; // variable declaration
6. int b; // variable declaration
7. a=b=80; // chained assignment
8. std::cout <<"Values of 'a' and 'b' are : " <<a<<","<<b<< std::endl;
9. return 0;
10. }

In the above code, we have declared two variables, i.e., 'a' and 'b'. Then, we have assigned the
same value to both the variables using chained assignment expression.

Output

Values of 'a' and 'b' are : 80,80

Note: Using chained assignment expression, the value cannot be assigned to the variable
at the time of declaration. For example, int a=b=c=90 is an invalid statement.

o Embedded Assignment Expression

An embedded assignment expression is an assignment expression in which assignment expression


is enclosed within another assignment expression.

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a; // variable declaration
6. int b; // variable declaration
7. a=10+(b=90); // embedded assignment expression
8. std::cout <<"Values of 'a' is " <<a<< std::endl;
9. return 0;
10. }

In the above code, we have declared two variables, i.e., 'a' and 'b'. Then, we applied embedded
assignment expression (a=10+(b=90)).

Output

Values of 'a' is 100

o Compound Assignment
A compound assignment expression is an expression which is a combination of an assignment
operator and binary operator.

For example,

1. a+=10;

In the above statement, 'a' is a variable and '+=' is a compound statement.

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=10; // variable declaration
6. a+=10; // compound assignment
7. std::cout << "Value of a is :" <<a<< std::endl; // displaying the value of a.
8. return 0;
9. }

In the above code, we have declared a variable 'a' and assigns 10 value to this variable. Then, we
applied compound assignment operator (+=) to 'a' variable, i.e., a+=10 which is equal to (a=a+10).
This statement increments the value of 'a' by 10.

Output

Value of a is :20
C++ Functions
The function in C++ language is also known as procedure or subroutine in other
programming languages.

To perform any task, we can create function. A function can be called many times. It
provides modularity and code reusability.

Advantage of functions in C
There are many advantages of functions.

1) Code Reusability

By creating functions in C++, you can call it many times. So we don't need to write the
same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number
or not. Without using function, you need to write the prime number logic 3 times. So,
there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it
several times.

Types of Functions
There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C++ header files such
as ceil(x), cos(x), exp(x), etc.

2. User-defined functions: are the functions which are created by the C++
programmer, so that he/she can use it many times. It reduces complexity of a big
program and optimizes the code.
Declaration of a function
The syntax of creating function in C++ language is given below:

1. return_type function_name(data_type parameter...)


2. {
3. //code to be executed
4. }

C++ Function Example


Let's see the simple example of C++ function.

1. #include <iostream>
2. using namespace std;
3. void func() {
4. static int i=0; //static variable
5. int j=0; //local variable
6. i++;
7. j++;
8. cout<<"i=" << i<<" and j=" <<j<<endl;
9. }
10. int main()
11. {
12. func();
13. func();
14. func();
15. }

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

Call by value and call by reference in C++


There are two ways to pass value or data to function in C language: call by value and
call by reference. Original value is not modified in call by value but it is modified in call
by reference.

Let's understand call by value and call by reference in C++ language one by one.
Call by value in C++
In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function
parameter in stack memory location. If you change the value of function parameter, it is
changed for the current function only. It will not change the value of variable inside the
caller method such as main().

Let's try to understand the concept of call by value in C++ language by the example
given below:

1. #include <iostream>
2. using namespace std;
3. void change(int data);
4. int main()
5. {
6. int data = 3;
7. change(data);
8. cout << "Value of the data is: " << data<< endl;
9. return 0;
10. }
11. void change(int data)
12. {
13. data = 5;
14. }

Output:

Value of the data is: 3

Call by reference in C++


In call by reference, original value is modified because we pass reference (address).
Here, address of the value is passed in the function, so actual and formal arguments
share the same address space. Hence, value changed inside the function, is reflected
inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of
pointers.

Let's try to understand the concept of call by reference in C++ language by the example
given below:

1. #include<iostream>
2. using namespace std;
3. void swap(int *x, int *y)
4. {
5. int swap;
6. swap=*x;
7. *x=*y;
8. *y=swap;
9. }
10. int main()
11. {
12. int x=500, y=100;
13. swap(&x, &y); // passing value to function
14. cout<<"Value of x is: "<<x<<endl;
15. cout<<"Value of y is: "<<y<<endl;
16. return 0;
17. }

Output:

Value of x is: 100


Value of y is: 500

Difference between call by value and call by reference


in C++
No. Call by value Call by reference

1 A copy of value is passed to An address of value is


the function passed to the function

2 Changes made inside the Changes made inside the


function is not reflected on function is reflected outside
other functions the function also

3 Actual and formal arguments Actual and formal arguments


will be created in different will be created in same
memory location memory location

C++ Recursion
When function is called within the same function, it is known as recursion in C++. The
function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is known as
tail recursion. In tail recursion, we generally call the same function with return
statement.

Let's see a simple example of recursion.

1. recursionfunction(){
2. recursionfunction(); //calling self function
3. }

C++ Recursion Example


Let's see an example to print factorial number using recursion in C++ language.

1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int factorial(int);
6. int fact,value;
7. cout<<"Enter any number: ";
8. cin>>value;
9. fact=factorial(value);
10. cout<<"Factorial of a number is: "<<fact<<endl;
11. return 0;
12. }
13. int factorial(int n)
14. {
15. if(n<0)
16. return(-1); /*Wrong value*/
17. if(n==0)
18. return(1); /*Terminating condition*/
19. else
20. {
21. return(n*factorial(n-1));
22. }
23. }

Output:

Enter any number: 5


Factorial of a number is: 120

We can understand the above program of recursive method call by the figure given
below:
C++ Storage Classes
Storage class is used to define the lifetime and visibility of a variable and/or function
within a C++ program.

Lifetime refers to the period during which the variable remains active and visibility refers
to the module of a program in which the variable is accessible.

There are five types of storage classes, which can be used in a C++ program

1. Automatic
2. Register
3. Static
4. External
5. Mutable

Storage Keyword Lifetime Visibility Initial


Class Value

Automatic auto Function Local Garbage


Block

Register register Function Local Garbage


Block
Mutable mutable Class Local Garbage

External extern Whole Global Zero


Program

Static static Whole Local Zero


Program

Automatic Storage Class


It is the default storage class for all local variables. The auto keyword is applied to all
local variables automatically.

1. {
2. auto int y;
3. float y = 3.45;
4. }

The above example defines two variables with a same storage class, auto can only be
used within functions.

Register Storage Class


The register variable allocates memory in register than RAM. Its size is same of register
size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

1. register int counter=0;

Static Storage Class


The static variable is initialized only once and exists till the end of a program. It retains
its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.
1. #include <iostream>
2. using namespace std;
3. void func() {
4. static int i=0; //static variable
5. int j=0; //local variable
6. i++;
7. j++;
8. cout<<"i=" << i<<" and j=" <<j<<endl;
9. }
10. int main()
11. {
12. func();
13. func();
14. func();
15. }

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

External Storage Class


The extern variable is visible to all the programs. It is used if two or more files are
sharing same variable or function.

1. extern int counter=0;

You might also like