C++ Notes 1
C++ Notes 1
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes
to structure software programs. It aims to implement real-world entities like inheritance, hiding,
polymorphism, etc., in programming. The main goal of OOP is to bind together the data and the
functions that operate on them so that no other part of the code can access this data except that
function
Class
A class is a user-defined data type that acts as a blueprint for creating objects. It consists of data
members and member functions, which can be accessed and used by creating an instance of that
class. For example, a Car class may have properties like wheels, speed limit, and mileage
Object
An object is an instance of a class and represents real-life entities. It contains data and code to
manipulate the data. For example, a Dog object may have characteristics like color, breed, bark,
sleep, and eat
Data Abstraction
Data abstraction refers to providing only essential information about the data to the outside
world, hiding the background details or implementation. For example, a driver knows that
pressing the accelerator increases the car's speed but does not know the inner mechanism
Encapsulation
Encapsulation is the wrapping up of data under a single unit. It binds together code and the data
it manipulates, hiding the data from other classes. For example, different sections in a company
handle their own data and do not allow direct access to other sections
Inheritance
Inheritance allows a class to derive properties and characteristics from another class. It enables
code reusability and reduces redundancy. For example, a Dog class can inherit properties from
an Animal class
Polymorphism
Polymorphism means having many forms. It allows a message to be displayed in more than one
form. For example, a person can be a father, a husband, and an employee at the same time
Dynamic Binding
UNIT II
Dynamic binding means that the code to be executed in response to a function call is decided at
runtime. It allows for more flexible and reusable code
Message Passing
Benefits of OOP
Code Reusability: OOP allows for the creation of reusable components, leading to less
duplication and more efficient development3.
Code Organization: It provides a clear and logical structure, making the code easier to
understand, maintain, and debug3.
DRY Principle: OOP supports the "Don't Repeat Yourself" principle, minimizing code
repetition and leading to cleaner, more maintainable code3.
Faster Development: By reusing existing code and creating modular components, OOP
allows for quicker and more efficient application development3.
Below are some of the differences between procedural and object-oriented programming:
The character set is a combination of English language comprising of the Alphabets and the White
spaces and some symbols from the mathematics including the Digits and the Special symbols. C++
character set means the characters and the symbols that are understandable and acceptable by the
C++ Program. These are grouped to create and give the commands, expressions, words, c-
statements, and some of the other tokens for the C++ Language.
It is basically the combination of alphabets or characters, special symbols, digits, and white spaces
that are similar as the learning English is to initially learns the alphabets, then learn how to combine
these alphabets to create words, which in turn are joined to make sentences and sentences are joined
to create the paragraphs. More about a C++ program we can say is that it is basically an order of the
characters arranged in a sequence. These characters come from the character set and play various
roles in many ways in the C++ compiler.
In addition to characters, C++ also uses a mixture of characters to represent some special conditions
as well. For example; Character combinations like ‘\nt, ‘\b’ and ‘\t’ are used for the representation
of the newline, backspace, and the horizontal tab correspondingly.
1. Alphabets
The alphabets are symbolized by A-Z & a-z, whichever is applicable. C- Language is case sensitive
so it always takes dissimilar meanings for the lower case and the upper case letters. By the use of
this character set C statements and character constants are writable very easily. Thus, all 26 letters
are usable in C-programming.
2. Digits
The digits are symbolized from 0-9 or by combining these digits together. With the use of digits, the
numeric constant is easily writable. The numeric data can also be assigned to the C-tokens as well.
All the 10 digits starting from 0 and ending at 9 are usable in the C-programming.
UNIT II
3. Special Symbols
All of the total keyboard keys excluding the alphabets, digits, and white spaces are termed as the
special symbols. Thus, these are some punctuation marks as well as some special symbols usable
for some special purpose or quotation.
There is a total of thirty special symbols that we can use in the C-programming. Moreover, special
symbols are usable for the C-statements like; to make an arithmetic statement +, -, * etc., for
creating relational statement <, >, <=, >=, == etc. , for creating assignment statement =, for creating
logical statement &&, II etc. are necessary.
4. White Spaces
White spaces have blank space, newline return, tab space (Horizontal), Form feed, carriage ctrl, etc.
are all usable for special purposes. Notably, Turbo-C Compiler always disregards these white space
characters in both high-level programming as well in low-level programming.
C++ Tokens
In C++, tokens can be defined as the smallest building block of C++ programs that the
compiler understands. Every word in a C++ source code can be considered a token.
We have several types of tokens each of which serves a specific purpose in the syntax and
semantics of C++. Below are the main types of tokens in C++:
1. Identifiers
2. Keywords
3. Constants
4. Strings
5. Special Symbols
6. Operators
UNIT II
1. Identifiers
In C++, entities like variables, functions, classes, or structs must be given unique names within
the program so that they can be uniquely identified. The unique names given to these entities
are known as identifiers.
It is recommended to choose valid and relevant names of identifiers to write readable and
maintainable programs. Keywords cannot be used as an identifier because they are reserved
words to do specific tasks. In the below example, “first_name’ is an identifier.
2. An identifier can consist of letters (A-Z or a-z), digits (0-9), and underscores (_). White
spaces and Special characters can not be used as the name of an identifier.
3. Keywords cannot be used as an identifier because they are reserved words to do specific
tasks. For example, string, int, class, struct, etc.
2. Keywords
Keywords in C++ are the tokens that are the reserved words in programming languages that
have their specific meaning and functionalities within a program. Keywords cannot be used as
an identifier to name any variables.
For example, a variable or function cannot be named as ‘int’ because it is reserved for
declaring integer data type.
There are 95 keywords reserved in C++. Some of the main Keywords are:
3. Constants
Constants are the tokens in C++ that are used to define variables at the time of initialization
and the assigned value cannot be changed after that.
We can define the constants in C++ in two ways that are using the ‘const’ keyword and
‘#define’ preprocessor directive. Let’s see both methods one by one.
Constants are the values that do not change during the execution of the program once defined.
We can make constant any type of data such as integer, float, string, and characters. A literal is
a constant value assigned to a constant variable.
Syntax
#define preprocessor can be used to define constant identifiers and the identifier is replaced
with the defined value throughout the program where ever it is used. It is defined globally
outside the main function.
Syntax
// The constant_Name is replaced by its value throughout the program where ever it is used
#define constant_Name value
4. Strings
UNIT II
In C++, a string is not a built-in data type like ‘int’, ‘char’, or ‘float’. It is a class available in
the STL library which provides the functionality to work with a sequence of characters, that
represents a string of text.
When we define any variable using the ‘string’ keyword we are actually defining an object that
represents a sequence of characters. We can perform various methods on the string provided by
the string class such as length(), push_backk(), and pop_back().
string variable_name;
Initialize the string object with string within the double inverted commas (“).
5. Special Symbols
Special symbols are the token characters having specific meanings within the syntax of the
programming language. These symbols are used in a variety of functions, including ending the
statements, defining control statements, separating items, and more.
Below are the most common special symbols used in C++ programming:
Scope resolution (::): Scope resolution operator is used to access members of namespaces,
classes, etc.
Dot (.): Dot operator also called member access operator used to access class and struct
members.
6. Operators
UNIT II
C++ operators are special symbols that are used to perform operations on operands such as
variables, constants, or expressions. A wide range of operators is available in C++ to perform a
specific type of operations which includes arithmetic operations, comparison operations,
logical operations, and more.
For example (A+B), in which ‘A’ and ‘B’ are operands, and ‘+’ is an arithmetic operator
which is used to add two operands.
Types of Operators
1. Unary Operators
2. Binary Operators
3. Ternary Operators
1. Unary Operators
Unary operators are used with single operands only. They perform the operations on a single
variable. For example, increment and decrement operators.
2. Binary Operators
They are used with the two operands and they perform the operations between the two
variables. For example (A<B), less than (<) operator compares A and B, returns true if A is
less than B else returns false.
Comparison Operators: These operators are used to compare two operands and they
include ‘==’, ‘!=’, ‘<‘, ‘>’, ‘<=’, and ‘>=’.
Logical Operators: These operators perform logical operations on boolean values. They
include ‘&&’, ‘||’, and ‘!‘.
Assignment Operators: These operators are used to assign values to variables and they
include ‘variables‘, ‘-=‘, ‘*=‘, ‘/=‘, and ‘%=’.
3. Ternary Operator
The ternary operator is the only operator that takes three operands. It is also known as a
conditional operator that is used for conditional expressions.
Syntax:
In this article, we will discuss operator precedence, operator associativity, and precedence
table according to which the priority of the operators in expression is decided in C language.
The following tables list the C operator precedence from highest to lowest and the associativity
for each of the operators:
Operator
Precedence Description Associativity
Operator
Precedence Description Associativity
* Dereference Operator
Operator
Precedence Description Associativity
12 || Logical OR Left-to-Right
= Assignment
Operator
Precedence Description Associativity
Easy Trick to Remember the Operators Associtivity and Precedence: PUMA’S REBL TAC
Operator Precedence in C
Operator precedence determines which operation is performed first in an expression with more
than one operator with different precedence.
10 + 20 * 30
The expression contains two operators, + (plus), and * (multiply). According to the given table,
the * has higher precedence than + so, the first evaluation will be
10 + (20 * 30)
10 + 600
610
[GFGTABS]C
#include <stdio.h>
int main()
return 0;
[/GFGTABS]
Output
10 + 20 * 30 = 610
As we can see, the expression is evaluated as,10 + (20 * 30) but not as (10 + 20) * 30 due to *
operator having higher precedence.
Operator Associativity
Operator associativity is used when two operators of the same precedence appear in an
expression. Associativity can be either from Left to Right or Right to Left.
100 / 5 % 2
Both / (division) and % (Modulus) operators have the same precedence, so the order of
evaluation will be decided by associativity.
According to the given table, the associativity of the multiplicative operators is from Left to
Right. So,
(100 / 5) % 2
20 % 2
[GFGTABS]C
#include <stdio.h>
int main()
return 0;
[/GFGTABS]
Output
100 / 5 % 2 = 0
Operators Precedence and Associativity are two characteristics of operators that determine
the evaluation order of sub-expressions.
Here, we have four operators, in which the / and * operators have the same precedence but have
higher precedence than the + and – operators. So, according to the Left-to-Right associativity
of / and *, / will be evaluated first.
= 100 + 20 - 3 * 10
= 100 + 20 - 30
= 120 - 30
exp = 120 - 30
= 90
[GFGTABS]C
#include <stdio.h>
int main()
// example
return 0;
[/GFGTABS]
Output:
100 + 200 / 10 – 3 * 10 = 90
Important Points
There are a few important points and cases that we need to remember for operator associativity
and precedence which are as follows:
1. Associativity is only used when there are two or more operators of the same precedence.
The point to note is associativity doesn’t define the order in which operands of a single operator
are evaluated. For example, consider the following program, associativity of the + operator is
left to right, but it doesn’t mean f1() is always called before f2(). The output of the following
program is in-fact compiler-dependent.
Example
[GFGTABS]C
#include <stdio.h>
int x = 0;
int f1()
{
UNIT II
x = 5;
return x;
int f2()
x = 10;
return x;
int main()
return 0;
[/GFGTABS]
Output
10
Parenthesis ( ) got the highest priority among all the C operators. So, if we want to change the
order of evaluation in an expression, we can enclose that particular operator in ( )
parenthesis along with its operands.
Example
100 + 200 / 10 - 3 * 10
UNIT II
= 90
But if we enclose 100 + 200 in parenthesis, then the result will be different.
(100 + 200) / 10 - 3 * 10 = 0
=0
2. All operators with the same precedence have the same associativity.
This is necessary, otherwise, there won’t be any way for the compiler to decide the evaluation
order of expressions that have two operators of the same precedence and different associativity.
For example + and – have the same associativity.
The precedence of postfix ++ is more than prefix ++, their associativity is also different. The
associativity of postfix ++ is left to right and the associativity of prefix ++ is right to left.
See this for examples.
4. Comma has the least precedence among all operators and should be used carefully.
Example
[GFGTABS]C
#include <stdio.h>
int main()
int a;
a = 1, 2, 3; // Evaluated as (a = 1), 2, 3
printf("%d", a);
return 0;
UNIT II
[/GFGTABS]
Output
In Python, an expression like “c > b > a” is treated as “c > b and b > a”, but this type of chaining
doesn’t happen in C. For example, consider the following program. The output of the following
program is “FALSE”.
Example
[GFGTABS]C
#include <stdio.h>
int main()
// is left to right. Therefore the value becomes ((30 > 20) > 10)
if (c > b > a)
printf("TRUE");
else
printf("FALSE");
return 0;
UNIT II
All variables use data type during declaration to restrict the type of data to be stored. Therefore,
we can say that data types are used to tell the variables the type of data they can store. 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.
C++ supports a wide variety of data types and the programmer can select the data type
appropriate to the needs of the application. Data types specify the size and types of values to be
stored. However, storage representation and machine instructions to manipulate each data type
differ from machine to machine, although C++ instructions are identical on all machines.
To explore data types and their applications in detail, our Complete C++ Course covers primitive
and advanced data types with practical coding exercises.
UNIT II
1. Primitive Data Types: These data types are built-in or predefined data types and can be used
directly by the user to declare variables. example: int, char, float, bool, etc. Primitive data types
available in C++ are:
Integer
Character
Boolean
Floating Point
UNIT II
Valueless or Void
Wide Character
2. Derived Data Types: Derived 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
Pointer
Reference
3. Abstract or User-Defined Data Types: Abstract or User-Defined data types are defined by
the user itself. Like, defining a class in C++ or a structure. C++ provides the following user-
defined datatypes:
Class
Structure
Union
Enumeration
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.
UNIT II
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.
sizeof() operator: sizeof() operator is used to find the number of bytes occupied by a
variable/data type in computer memory.
Example:
int m , x[50];
cout<<sizeof(m); //returns 4 which is the number of bytes occupied by the integer variable
“m”.
cout<<sizeof(x); //returns 200 which is the number of bytes occupied by the integer array
variable “x”.
The size of variables might be different from those shown in the above table, depending on the
compiler and the computer you are using.
C++
#include <iostream>
4
UNIT II
int main()
10
11
12
13
14
15
16
return 0;
UNIT II
17
Output
Size of char : 1
Size of int : 4
Size of long : 8
Size of float : 4
Size of double : 8
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.
UNIT II
Signed
Unsigned
Short
Long
The below table summarizes the modified size and range of built-in datatypes when combined
with the type modifiers:
Note: Above values may vary from compiler to compiler. In the above example, we have
considered GCC 32 bit.
UNIT II
We can display the size of all the data types by using the sizeof() operator and passing the
keyword of the datatype, as an argument to this function as shown below:
Now to get the range of data types refer to the following chart
Note: syntax<limits.h> header file is defined to find the range of fundamental data-types.
Unsigned modifiers have minimum value is zero. So, no macro constants are defined for the
unsigned minimum value.
Macro Constants
Name Expresses
Name Expresses
LLONG_MIN The minimum value for an object of type long long int
ULLONG_MAX Maximum value for an object of type Unsigned long long int
The actual value depends on the particular system and library implementation but shall reflect
the limits of these types in the target platform. LLONG_MIN, LLONG_MAX, and
ULLONG_MAX are defined for libraries complying with the C standard of 1999 or later (which
only includes the C++ standard since 2011: C++11).
C++ Program to Find the Range of Data Types using Macro Constants
Example:
UNIT II
C++
#include <iostream>
#include <limits.h>
int main()
cout << "Size of char : " << sizeof(char) << " byte"
<< endl;
10
11
UNIT II
cout << "char minimum value: " << CHAR_MIN << endl;
12
13
cout << "char maximum value: " << CHAR_MAX << endl;
14
15
cout << "Size of int : " << sizeof(int) << " bytes"
16
<< endl;
17
18
19
20
21
22
23
UNIT II
24
25
26
27
28
29
30
cout << "Size of float : " << sizeof(float) << " bytes"
31
<< endl;
32
33
34
35
36
UNIT II
37
38
39
return 0;
40
Output
C++
UNIT II
#include <iostream>
#include <string>
int main() {
int a = 10;
short b = 20;
long c = 30;
10
11
12
13
14
15
16
17
18
float e = 3.14f;
19
double f = 3.141592;
20
21
22
23
24
UNIT II
25
26
27
char h = 'a';
28
wchar_t i = L'b';
29
char16_t j = u'c';
30
char32_t k = U'd';
31
32
33
34
35
36
UNIT II
37
38
bool l = true;
39
bool m = false;
40
41
42
43
44
45
46
47
48
49
UNIT II
return 0;
50
Output
int: 10
short: 20
long: 30
long long: 40
float: 3.14
double: 3.14159
char: a
wchar_t: b
char16_t: 99
char32_t: 100
true: 1
false: 0
Hello, world!
UNIT II