C++ & DS-Unit 1
C++ & DS-Unit 1
20BHM202
Unit 1
BY
SYED JAMALULLAH R
C++ Fundamentals:
The prime purpose of C++ programming was to add object orientation to the C programming language, which is in
itself one of the most powerful programming languages. The core of the pure object-oriented programming is to
create an object, in code, that has certain properties and methods. While designing C++ modules, we try to see whole
world in the form of objects. For example a car is an object which has certain properties such as colour, number of
doors, and the like. It also has certain methods such as accelerate, brake, and so on.
Object
This is the basic unit of object oriented programming. That is both data and function that operate on data are bundled
as a unit called as object.
Class
When you define a class, you define a blueprint for an object. This doesn't actually define any data, but it does define
what the class name means, that is, what an object of the class will consist of and what operations can be performed
on such an object.
Abstraction
Data abstraction refers to, providing only essential information to the outside world and hiding their background
details, i.e., to represent the needed information in program without presenting the details.
For example, a database system hides certain details of how data is stored and created and maintained. Similar way,
C++ classes provides different methods to the outside world without giving internal detail about those methods and
data.
Encapsulation
Encapsulation is placing the data and the functions that work on that data in the same place. While working with procedural
languages, it is not always clear which functions work on which variables but object-oriented programming provides you
framework to place the data and the relevant functions together in the same object.
Inheritance
One of the most useful aspects of object-oriented programming is code reusability. As the name suggests Inheritance is the process
of forming a new class from an existing class that is from the existing class called as base class, new class is formed called as
derived class.
This is a very important concept of object-oriented programming since this feature helps to reduce the code size.
Polymorphism
The ability to use an operator or function in different ways in other words giving different meaning or functions to the operators or
functions is called polymorphism. Poly refers to many. That is a single function or an operator functioning in many ways different
upon the usage is called polymorphism.
Dynamic Binding
Dynamic binding or late binding is the mechanism a computer program waits until runtime to bind the name of a method called to
an actual subroutine. It is an alternative to early binding or static binding where this process is performed at compile-time.
Message Passing
In computer science, message passing is a technique for invoking behavior (i.e., running a program) on a computer. The invoking
program sends a message to a process (which may be an actor or object) and relies on that process and its supporting infrastructure
to then select and run some appropriate code.
OPERATORS
Operators are the foundation of any programming language. Thus the functionality of C/C++ programming language is incomplete without
the use of operators. We can define operators as symbols that help us to perform specific mathematical and logical computations on
operands.
There are following types of operators to perform different types of operations in C language.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operator
Unary operator
Ternary or Conditional Operator
Misc. Operator
Arithmetic Operator:
There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then −
Relational Operator:
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then −
Logical Operators:
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then −
Bitwise Operator:
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then
−
Assignment Operator:
There are following assignment operators supported by C++ language −
Misc. Operator:
The following table lists some other operators that C++ supports.
Unary Operator:
Unary operator are operators that act upon a single operand to produce a new value. The unary operators are as follows −
Indirection operator (*) - It operates on a pointer variable, and returns an l-value equivalent to the value at the pointer address. This is
called "dereferencing" the pointer.
Address-of operator (&) - The unary address-of operator (&) takes the address of its operand. The operand of the address-of operator can
be either a function designator or an l-value that designates an object that is not a bit field and is not declared with the register storage-class
specifier.
Unary plus operator (+) - The result of the unary plus operator (+) is the value of its operand. The operand to the unary plus operator must
be of an arithmetic type.
Unary negation operator (-) - The - (unary minus)operator negates the value of the operand. The operand can have any arithmetic type.
The result is not an lvalue.
Logical negation operator (!) - The logical negation operator (!) reverses the meaning of its operand. The operand must be of arithmetic or
pointer type (or an expression that evaluates to arithmetic or pointer type). The operand is implicitly converted to type bool .
One's complement operator (~) - The one's complement operator, sometimes called the "bitwise complement" or "bitwise NOT" operator,
produces the bitwise one's complement of its operand. The operand must be of integral type.
Prefix increment operator (++) - The prefix increment operator ( ++ ) adds one to its operand; this incremented value is the result of the
expression. The operand must be an l-value not of type const. The result is an l-value of the same type as the operand.
Prefix decrement operator (--) - The prefix decrement operator ( -- ) subtracts one from its operand; this decremented value is the result of
the expression. The operand must be an l-value not of type const. The result is an l-value of the same type as the operand.
Cast operator () - A type cast provides a method for explicit conversion of the type of an object in a specific situation. The compiler treats
cast-expression as type type-name after a type cast has been made.
sizeof operator - It is a compile time unary operator which can be used to compute the size of its operand.
new operator - It is a memory allocation operator that is used to allocate memory dynamically.
delete operator - It is a memory allocation operator that is used to DE allocate memory that was dynamically allocated.
These operators have right-to-left associativity. Unary expressions generally involve syntax that precedes a postfix or primary expression.
The operator keyword declares a function specifying what operator-symbol means that once applied to instances of a class. this gives the
operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining
the types of its operands.
The unary operators operate on a single operand and following are the examples of Unary operators −
The increment (++) and decrement (--) operators.
The unary minus (-) operator.
The logical not (!) operator.
Ternary Operator/Conditional Operator:
The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows −
The first operand is implicitly converted to bool. It is evaluated and all side effects are completed before continuing.
If the first operand evaluates to true (1), the second operand is evaluated.
If the first operand evaluates to false (0), the third operand is evaluated.
The result of the conditional operator is the result of whichever operand is evaluated — the second or the third. Only one of the last two
operands is evaluated in a conditional expression. The evaluation of the conditional operator is very complex. The steps above were just a
quick intro to it. Conditional expressions have right-to-left associativity. The first operand must be of integral or pointer type. The following
rules apply to the second and third operands −
If both operands are of the same type, the result is of that type.
If both operands are of arithmetic or enumeration types, the usual arithmetic conversions (covered in Standard Conversions) are
performed to convert them to a common type.
If both operands are of pointer types or if one is a pointer type and the other is a constant expression that evaluates to 0, pointer
conversions are performed to convert them to a common type.
If both operands are of reference types, reference conversions are performed to convert them to a common type.
If both operands are of type void, the common type is type void.
If both operands are of the same user-defined type, the common type is that type.
If the operands have different types and at least one of the operands has user-defined type then the language rules are used to determine
the common type. (See warning below.)
Expressions and Control Structures:
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:
(a+b) - c
(x/y) -z
4a2 - 5b +c
(a+b) * (x+y)
An expression can be of following types:
Constant expressions
Integral expressions
Float expressions
Pointer expressions
Relational expressions
Logical expressions
Bitwise expressions
Special assignment 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:
It is used in the subscript declaratory to describe the array bound.
It is used after the case keyword in the switch statement.
It is used as a numeric value in an enum
It specifies a bit-field width.
It is used in the pre-processor #if
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:
(x * y) -5
x + int(9.0)
where x and y are the integers.
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:
x+y
(x/10) + y
34.5
x+float(10)
Pointer Expressions
A pointer expression is an expression that produces address value as an output.
The following are the examples of pointer expression:
&x
ptr
ptr++
ptr-
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:
a>b
a-b >= x-y
a+b>80
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:
a>b && x>y
a>10 || b==5
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.
Special assignment expressions are the expressions which can be further classified depending upon the value assigned to the variable.
Control Structures:
Control statements in both C and C++ specify the flow of program execution and which instructions of the program must be executed next.
Thus allowing programmer to make decisions, perform tasks properly. It important for programmer to know how a program execution
flows, for better understanding and fast debugging.
C/C++ provides four different styles of flow control:
Sequence control
Selection or Decision making statements
Repetition or iteration control
Jump statement
Selection or Decision making control statements
This statement has branches to follow depending on condition executed. Following are the decision making
statements used in C++
if statement
if takes an expression in parenthesis and a block of statements follow which executed only if the condition inside parenthesis is true.
Otherwise these block is skipped and note that expression will be assumed to be true if its evaluated values is non-zero.
Syntax:
if-else Statement
In addition to above if block else block added which execute only when IF block expression is false.
Syntax:
Nested if-else statement:
Using if-else block inside other if-else block is called Nested if-else. It is completely legal to use if-else inside another. This statement has
ability to control program flow based on multiple levels of condition.
Syntax:
Else-if ladder
Used when more than one condition need to be evaluated.
Syntax:
switch statement:
The switch statement is much like a nested if – else statement executes one or more of a series of cases, based on the value of an expression.
The switch expression is evaluated and integral promotions applied than compared with the constant expressions in the case labels.
Some features of switch statement:
The constant expression must be of an integral type
No two case label can be same.
There is no limit on the number of case labels in switch statement.
Only one default statement can present.
The cases and default labels can occur in any order, but it is common practice to put default statement after the cases.
Break Keyword: There should be a break statement between cases to prevent execution of other case statements and terminate switch
block.
If the switch expression value does not match any case label than the default statement is executed and if there is no default label, then
execution of the switch statement terminates.
Syntax:
Iteration Control Statements
Iteration control is a process where a set of instructions or block of statements repeated in a specified number of times or until a certain
condition became false.
Loops are classified into three major in C/C++ and 4th only in C++.
while loop
do-while loop
for loop
Nested loop
while loop
The while loop statement allows the programmer to specify that a program should repeat set of instruction inside the block till the condition
remains true. While is the most basic loop in C/C++. While loop is Entry Controlled loop.
Basic syntax of while loop:
do – while loop
The do – while loop is similar to the while statement. In do – while loop, the test condition is executed after the
execution of loop body. So, irrespective of what the test condition is this loop get executed at least once. Do-
While loop is Exit Controlled loop.
Basic syntax of do…while loop:
for loop
for loop is almost similar to while loop. The for loop statement allows the programmer to specify that a
program should repeat set of instruction inside the block till specific number of times the condition remains
true. For loop is Entry Controlled loop.
Basic syntax of for loop:
int main() {
cout << setw(20) << setfill('*') << "w3schools.in" << setw(20) << setfill('*')<<"Test"<< endl;
}
Pointers in C++:
A pointer is a variable that stores the memory address as its value. A Pointer value points to the data type (like int or string) of the same type
and it is created with the (*) Operator. The address of the variable you're working with is assigned to the pointer:
Explanation:
Create the pointer variable with the same name ptr, that points to a string variable, by using the asterisk sign (*)(string * pointer). Note that
the type of the pointer has to match the type of the variable you're working with.
Use the & Operator to store the memory address of the variable called food, and assign it to the pointer. Now, ptr holds the value of food
memory address.
Arrays in C++:
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
To declare an array, define the variable type, specify the name of the array followed by square brackets and specify the number of elements it
should store:
string cars[4];
We have now declared a variable that holds an array of four strings. To insert values to it, we can use an array literal - place the values in a
comma-separated list, inside curly braces:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};