C++ Short Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

C++ EBook

By @Curious_.programmer

Copyrighted By @Curious_.programmer
Introduction to C++
 History of C++a
 C++ Standards
 Basic Structure of a C++ Program

Variables and Data Types


 Declaring Variables
 Data Types
 Constants

Operators and Expressions


 Arithmetic Operators
 Comparison Operators
 Logical Operators
 Bitwise Operators

Control Flow Statements


 If-else Statements
 Switch Statements
 Loops
 Jump Statements

Functions
 Defining Functions
 Function Overloading
 Recursion

PDF File Uploaded On Telegram ( Link In Bio)


Arrays and Pointers
 Declaring Arrays
 Multidimensional Arrays
 Pointers and Addresses
 Dynamic Memory Allocation

Classes and Objects


 Defining Classes
 Access Control
 Constructors and Destructors
 Inheritance
 Polymorphism

Exception Handling
 Try-catch Blocks
 Throwing Exceptions
 Standard Exception Classes

Templates
 Function Templates
 Class Templates
 Template Specialization

Standard Template Library (STL)


 Containers
 Algorithms
 Iterators

File Handling
 File Input and Output
PDF File Uploaded On Telegram ( Link In Bio)
 File Pointers
 Binary Files

Advanced Topics
 Lambda Expressions
 Move Semantics
 Smart Pointers
 Multithreading

PDF File Uploaded On Telegram ( Link In Bio)


 C++ is a high-level, general-purpose programming language that was
developed in the early 1980s by Bjarne Stroustrup at Bell Labs.
 It was designed as an extension of the C programming language with
additional features such as classes, objects, inheritance, and
polymorphism.
 C++ is widely used for developing applications ranging from operating
systems and device drivers to games, financial software, and scientific
simulations.

History of C++:
 C++ was developed by Bjarne Stroustrup at Bell Labs in 1983 as an
extension of the C language.
 The first commercial implementation of C++ was released in 1985 by
AT&T.
 The first ISO standard for C++ was published in 1998, and subsequent
updates have been released in 2003, 2011, 2014, 2017, and 2020.

C++ Standards:
 The C++ standards define the syntax, semantics, and library specifications
for the language.
 The latest C++ standard is C++20, which was published in 2020 and
includes several new features such as modules, concepts, coroutines, and
ranges.
 C++ standards are developed and maintained by the ISO C++ committee,
which includes experts from industry, academia, and standards
organizations.

PDF File Uploaded On Telegram ( Link In Bio)


Basic Structure of a C++ Program:
 A C++ program typically consists of one or more source files that are
compiled into object files and linked together to create an executable
program.
 The basic structure of a C++ program includes a header file that defines
any necessary classes or functions, a main function that serves as the
entry point for the program, and any necessary helper functions or classes.
 C++ programs can also include preprocessor directives, comments, and
other features that help to organize and document the code.

Variables and Data Types:


 Variables are named storage locations in a program that can hold data of a
certain type.
 C++ supports several types of data, including integers, floating-point
numbers, characters, Boolean values, and user-defined types such as
classes and structures.
 Before using a variable, it must be declared with a data type and
optionally initialized with a value.

Declaring Variables:
 To declare a variable in C++, you must specify its data type followed by its
 For example, to declare an integer variable named "age", you would write
"int age;".Variables can also be initialized with an initial value using the
assignment operator, such as "int age = 30;".

PDF File Uploaded On Telegram ( Link In Bio)


Data Types:
 C++ supports several built-in data types, including:
 Integers, such as "int" and "long".
 Floating-point numbers, such as "float" and "double".
 Characters, such as "char".
 Boolean values, which are represented by the "bool" data type.
 C++ also supports user-defined data types such as classes and structures.

Constants:
 Constants are values that cannot be changed during program execution.
 C++ supports two types of constants: literal constants and symbolic
constants.
 Literal constants are values that are explicitly written into the program
code, such as "5" or "'A'".
 Symbolic constants are defined using the "const" keyword and can be
given a meaningful name, such as "const double PI = 3.14159;".

Operators and Expressions:


 Operators are symbols that perform operations on one or more operands
to produce a result.
 C++ supports several types of operators, including arithmetic operators,
comparison operators, logical operators, and bitwise operators.
 Expressions are combinations of operators and operands that produce a
value.

Arithmetic Operators:
 Arithmetic operators are used to perform mathematical calculations.
 C++ supports several arithmetic operators, including addition (+),
subtraction (-), multiplication (*), division (/), and modulus (%).
 For example, the expression "int result = 5 + 3 * 2;" would assign the value
11 to the variable "result".
PDF File Uploaded On Telegram ( Link In Bio)
Comparison Operators:
 Comparison operators are used to compare values and produce a Boolean
result.
 C++ supports several comparison operators, including equals (==), not
equals (!=), less than (<), less than or equal to (<=), greater than (>), and
greater than or equal to (>=).
 For example, the expression "bool result = (5 > 3);" would assign the value
"true" to the variable "result".

Logical Operators:
 Logical operators are used to combine Boolean values and produce a
Boolean result.
 C++ supports several logical operators, including AND (&&), OR (||), and
NOT (!).
 For example, the expression "bool result = (x > 0 && y < 0);" would assign
the value "true" to the variable "result" if both conditions are true.

Bitwise Operators:
 Bitwise operators are used to perform operations on individual bits in a
binary number.
 C++ supports several bitwise operators, including bitwise AND (&), bitwise
OR (|), bitwise XOR (^), bitwise NOT (~), left shift (<<), and right shift (>>).
 For example, the expression "int result = 5 & 3;" would assign the value 1
to the variable "result", because the bitwise AND operation produces a
binary value of 000001.

PDF File Uploaded On Telegram ( Link In Bio)


Control Flow Statements:
Control flow statements are used to control the flow of a program's
execution. C++ supports several types of control flow statements,
including if-else statements, switch statements, loops, and jump
statements.

PDF File Uploaded On Telegram ( Link In Bio)


If-else Statements:
If-else statements are used to execute code based on a condition. The
syntax for an if-else statement is as follows:

For example:

Switch Statements:

PDF File Uploaded On Telegram ( Link In Bio)


Switch statements are used to execute different blocks of code based
on the value of a variable. The syntax for a switch statement is as
follows:

For example:

PDF File Uploaded On Telegram ( Link In Bio)


Loops:
Loops are used to execute a block of code repeatedly. C++ supports
several types of loops, including for loops, while loops, and do-while
loops.

For example:

Jump Statements:
Jump statements are used to transfer control to a different part of the
program. C++ supports several types of jump statements, including
break, continue, and goto.

PDF File Uploaded On Telegram ( Link In Bio)


For example:

PDF File Uploaded On Telegram ( Link In Bio)


Functions:

In C++, a function is a group of statements that together perform a task.


Every C++ program has at least one function, which is the main()
function.

Defining Functions:

A function definition consists of a function header and a function body.


The function header specifies the function's name, return type, and
parameters. The function body contains the statements that perform
the function's task.

Here is an example of a function definition:

PDF File Uploaded On Telegram ( Link In Bio)


This function is named add, takes two integer parameters x and y, and
returns an integer value that is the sum of x and y.

Function Overloading:
Function overloading is the ability to define multiple functions with the
same name but with different parameter types and/or numbers. When
a function is called, the correct version of the function is selected based
on the parameters provided.

Here is an example of function overloading:

This code defines two functions named add. The first function takes two
integer parameters and returns an integer value, while the second
function takes two double parameters and returns a double value.

PDF File Uploaded On Telegram ( Link In Bio)


Recursion:

Recursion is a technique where a function calls itself to perform a task.


Recursion can be used to solve problems that can be broken down into
smaller sub-problems.

Here is an example of a recursive function:

This function calculates the factorial of a number n using recursion. The


base case is when n is equal to 0, in which case the function returns 1.
Otherwise, the function calls itself with n - 1 as the argument and
multiplies the result by n.

PDF File Uploaded On Telegram ( Link In Bio)


Arrays and Pointers:

Arrays and pointers are fundamental concepts in C and C++


programming languages. In these languages, arrays are used to store a
collection of similar data types, and pointers are used to store memory
addresses.

 Declaring Arrays:

In C and C++, arrays can be declared using the following syntax:

where data_type is the data type of the elements, array_name is the


name of the array, and array_size is the number of elements in the
array. For example, to declare an array of integers with 5 elements, you
would use the following code:

PDF File Uploaded On Telegram ( Link In Bio)


 Multidimensional Arrays:

A multidimensional array is an array that contains more than one


dimension. In other words, it is an array of arrays. The syntax for
declaring a two-dimensional array in C++ is as follows:

where data_type is the data type of the elements, array_name is the


name of the array, row_size is the number of rows, and column_size is
the number of columns. For example, to declare a two-dimensional
array of integers with 3 rows and 4 columns, you would use the
following code:

PDF File Uploaded On Telegram ( Link In Bio)


 Pointers and Addresses:

A pointer is a variable that stores the memory address of another


variable. Pointers are useful for manipulating memory directly and can
be used to pass values by reference. The syntax for declaring a pointer
in C++ is as follows:

Example:

PDF File Uploaded On Telegram ( Link In Bio)


 Dynamic Memory Allocation:

Dynamic memory allocation is a mechanism that allows us to allocate


memory at runtime. We can allocate memory dynamically in C++ using
the new keyword.

Example:

 Arrays and Pointers:

In C++, an array name is a constant pointer to the first element of the


array. We can use a pointer to access the elements of an array.

Example:

PDF File Uploaded On Telegram ( Link In Bio)


 Pointers and Functions:

We can pass pointers to functions as arguments. This allows us to


modify the original values of the variables outside the function.

Example:

 Classes and Objects :

 Defining Classes:

PDF File Uploaded On Telegram ( Link In Bio)


Classes are user-defined data types that can hold data and functions.
They allow us to encapsulate related data and behavior into a single
entity. For example:

 Access Control:

Access control specifies which data and functions of a class are


accessible to the outside world. There are three access specifiers:
private, protected, and public. For example:

PDF File Uploaded On Telegram ( Link In Bio)


Constructors and Destructors:
Constructors are special member functions that are called when an
object of a class is created. They initialize the object's data members.
Destructors are special member functions that are called when an
object of a class is destroyed. They clean up any resources that were
allocated during the object's lifetime. For example:

PDF File Uploaded On Telegram ( Link In Bio)


Inheritance:
In C++, inheritance is a mechanism that allows a new class to be based
on an existing class, inheriting its members and properties. This helps to
avoid code repetition and makes the code more organized and
maintainable.

Here's an example of a base class "Person" and a derived class


"Student" that inherits from Person:

PDF File Uploaded On Telegram ( Link In Bio)


five types of inheritance:

 Single inheritance: A derived class inherits from a single base class. For
example:
PDF File Uploaded On Telegram ( Link In Bio)
 Multiple inheritance: A derived class inherits from multiple base classes.
For example:

PDF File Uploaded On Telegram ( Link In Bio)


PDF File Uploaded On Telegram ( Link In Bio)
 Multilevel inheritance: A derived class is created from another derived
class. For example:

PDF File Uploaded On Telegram ( Link In Bio)


 Hierarchical inheritance: Multiple derived classes are created from a single
base class. For example:

PDF File Uploaded On Telegram ( Link In Bio)


 Hybrid inheritance: A combination of multiple inheritance and multilevel
inheritance. For example:

PDF File Uploaded On Telegram ( Link In Bio)


Polymorphism:
In C++, polymorphism is the ability of an object to take on many forms.
This is achieved through function overloading, operator overloading,
and virtual functions.

Here's an example of a class hierarchy that uses virtual functions for


runtime polymorphism:

PDF File Uploaded On Telegram ( Link In Bio)


In the example above, the "Shape" class is a base class that defines a
virtual function "draw()". The "Circle" and "Rectangle" classes are
derived from "Shape", and they override the "draw()" function with
their own implementations.

At runtime, we can create objects of the "Circle" and "Rectangle"


classes, and store their addresses in a pointer of the "Shape" class.
PDF File Uploaded On Telegram ( Link In Bio)
When we call the "draw()" function using the pointer, the correct
version of the function is called based on the type of object pointed to
by the pointer. This is an example of runtime polymorphism.

PDF File Uploaded On Telegram ( Link In Bio)


Exception handling :

Exception handling is a mechanism in C++ to handle unexpected or


exceptional conditions that occur during the execution of a program.
These conditions are often referred to as exceptions or errors, and they
can arise due to a variety of reasons, such as invalid user input, system
failures, or resource unavailability.

To handle these exceptions, C++ provides a set of keywords and


constructs that allow you to write code that detects and responds to
exceptions in a controlled manner. The three primary keywords for
exception handling are:

 Try: This keyword is used to enclose a block of code that might throw an
exception.

PDF File Uploaded On Telegram ( Link In Bio)


 Catch: This keyword is used to define a block of code that executes when
an exception is thrown.

 Throw: This keyword is used to explicitly throw an exception from a block


of code.

Here's an example of exception handling in C++:

PDF File Uploaded On Telegram ( Link In Bio)


In this example, the user is prompted to enter two numbers, which are
then used to perform a division operation. However, before the division
is performed, the code checks whether the second number is zero,
which would result in a division by zero error. If the second number is
indeed zero, the code throws an exception with the message "Division
by zero!".

The try block in this example encloses the division operation and the
catch block defines a block of code that will execute if an exception is
thrown. In this case, the catch block simply prints the error message to
the console.

PDF File Uploaded On Telegram ( Link In Bio)


C++ also provides a set of standard exception classes, which can be used
to handle specific types of exceptions. These include:

 std::exception: This is the base class for all standard exceptions.

 std::logic_error: This class is used for logical errors, such as invalid


arguments or incorrect use of an object.

 std::runtime_error: This class is used for runtime errors, such as file I/O
errors or memory allocation failures.

Here's an example of using a standard exception class in C++:

PDF File Uploaded On Telegram ( Link In Bio)


In this example, a std::runtime_error exception is thrown if the second
number is zero. The catch block then catches this exception and prints
the error message to the console using the what() function of the
exception object.

 Templates:

PDF File Uploaded On Telegram ( Link In Bio)


Templates in C++ provide a way to create generic functions and classes
that can work with different data types without rewriting the code.
There are three types of templates in C++: Function templates, class
templates, and template specialization.

 Function Templates:

Function templates are used to define a generic function that can


operate on different data types. It allows you to write a single function
that can be used for different data types. For example, the following
function template calculates the maximum of two values:

 Class Templates:

Class templates are used to define a generic class that can work with
different data types. It allows you to write a single class that can be
used for different data types. For example, the following class template
defines a stack:

PDF File Uploaded On Telegram ( Link In Bio)


 Template Specialization:

Template specialization is a way to provide a specialized


implementation of a template for a specific data type. For example, you
can define a specialized implementation of the max function template
for the string data type as follows:

PDF File Uploaded On Telegram ( Link In Bio)


 Standard Template Library (STL)

 Containers: STL provides a set of containers, which are classes that can
hold a collection of elements. Examples of containers include vector,
deque, list, set, and map. Containers can be used to store and manipulate
data efficiently.

 Algorithms: STL also provides a set of algorithms, which are functions that
operate on containers. Examples of algorithms include sorting, searching,
and modifying elements in a container. Algorithms can be used to perform
complex operations on containers without having to write complex code.

 Iterators: STL provides a set of iterators, which are objects that can be
used to traverse containers. Iterators provide a way to access the
elements in a container one at a time, and can be used in combination
with algorithms to perform operations on containers.

Here's a brief example of using STL:

PDF File Uploaded On Telegram ( Link In Bio)


In this example, we create a vector of integers and initialize it with some
values. We then use the std::sort algorithm to sort the vector, and
finally use an iterator to print the sorted vector.

 File Handling

 File Handling: This topic covers how to read from and write to files in C++.
It includes concepts like file input/output, file pointers, and binary files.

 File Input and Output: This involves reading data from and writing data to
files. In C++, files are opened using streams, which are objects that
represent input/output sources. File input involves reading data from a file
into a program, while file output involves writing data from a program to a
file.

PDF File Uploaded On Telegram ( Link In Bio)


 File Pointers: File pointers are used to keep track of the position of the
next byte to be read from or written to a file. They can be moved to any
position within a file to read or write data from that location.

 Binary Files: Binary files are files that contain data in a binary format,
rather than a text format. They are often used to store complex data
structures, such as arrays and structures, in a compact and efficient way.

Overall, file handling is an important topic in C++ programming, as it


allows programs to read and write data to files, which is essential for
many applications.

 Advanced Topics :

 Lambda Expressions:

Lambda expressions allow you to define small, anonymous functions


that can be passed as arguments to other functions. Here's an example
of a lambda expression that adds two numbers:

 Move Semantics:

PDF File Uploaded On Telegram ( Link In Bio)


Move semantics is a feature of C++ that allows you to transfer
ownership of an object from one place to another, rather than copying
it. This can be more efficient in some cases, especially for large objects.
Here's an example of moving a string from one variable to another:

 Smart Pointers:

Smart pointers are a type of pointer that automatically manage the


memory of the object they point to. There are three types of smart
pointers in C++: unique_ptr, shared_ptr, and weak_ptr. Here's an
example of using a unique_ptr:

 Multithreading:
PDF File Uploaded On Telegram ( Link In Bio)
Multithreading allows your program to run multiple threads of
execution simultaneously. This can be useful for tasks that can be split
into smaller pieces that can be executed in parallel. Here's an example
of creating a simple thread that prints out "Hello, world!":

PDF File Uploaded On Telegram ( Link In Bio)

You might also like