0% found this document useful (0 votes)
9 views28 pages

C++ & Data Structures (Unit-1)

C++ is a general-purpose programming language developed to enhance C with object-oriented features, making it suitable for various applications like embedded systems and game engines. It combines high-level language features with low-level capabilities, offering advantages such as modularity, data encapsulation, and polymorphism. Key concepts of C++ include classes, objects, encapsulation, abstraction, inheritance, and dynamic binding, which facilitate efficient and maintainable programming.

Uploaded by

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

C++ & Data Structures (Unit-1)

C++ is a general-purpose programming language developed to enhance C with object-oriented features, making it suitable for various applications like embedded systems and game engines. It combines high-level language features with low-level capabilities, offering advantages such as modularity, data encapsulation, and polymorphism. Key concepts of C++ include classes, objects, encapsulation, abstraction, inheritance, and dynamic binding, which facilitate efficient and maintainable programming.

Uploaded by

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

Introduction to C++

C++ is a general-purpose programming language that was developed by Bjarne


Stroustrup as an enhancement of the C language to add object-oriented
paradigm.
 It is considered as a middle-level language as it combines features of
both high-level and low-level languages.
 It has high level language features like object oriented programming, exception
handling and templates along with low-level capabilities, such as direct memory
manipulation and system-level programming.
 It is used to build embedded systems, game engines, web browsers, compilers
and operating systems.

Features of C++
The main features C++ programming language are as follows:
 Simple: It is a simple language in the sense that programs can be broken down
into logical units and parts, and has a rich library support and a variety of
datatypes.
 Machine Independent: C++ code can be run on any machine as long as a
suitable compiler is provided.
 Low-level Access: C++ provides low-level access to system resources, which
makes it a suitable choice for system programming and writing efficient code.
 Fast Execution Speed: C++ is one of the fastest high-level languages. There is
no additional processing overhead in C++, it is blazing fast.
 Object-Oriented: One of the strongest points of the language which sets it
apart from C. Object-Oriented support helps C++ to make maintainable and
extensible programs. i.e. large-scale applications can be built.

First C++ Program


The below C++ code shows the basic structure of a program
#include <iostream>
using namespace std;

int main() {
cout << "Hello, World!";
return 0;
}

Output
Hello, World!
Advantage of OOPs
Here are key advantages of Object-Oriented Programming (OOP) over Procedure-
Oriented Programming (POP):
 Modularity and Reusability: OOP promotes modularity through classes and
objects, allowing for code reusability.
 Data Encapsulation: OOP encapsulates data within objects, enhancing data
security and integrity.
 Inheritance: OOP supports inheritance, reducing redundancy by reusing
existing code.
 Polymorphism: OOP allows polymorphism, enabling flexible and dynamic code
through method overriding.
 Abstraction: OOP enables abstraction, hiding complex details and exposing
only essential features

Procedural Programming vs Object-Oriented Programming

Below are some of the differences between procedural and object-oriented


programming:
Procedural Oriented Programming Object-Oriented Programming

In object-oriented programming, the


In procedural programming, the program is
program is divided into small parts
divided into small parts called functions.
called objects.

Procedural programming follows a top-down Object-oriented programming follows


approach. a bottom-up approach.

Object-oriented programming has access


There is no access specifier in procedural
specifiers like private, public, protected,
programming.
etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have any Object-oriented programming provides


proper way of hiding data so it is less secure. data hiding so it is more secure.

In procedural programming, overloading is Overloading is possible in object-oriented


not possible. programming.

In object-oriented programming, the


In procedural programming, there is no
concept of data hiding and inheritance is
concept of data hiding and inheritance.
used.

In procedural programming, the function is In object-oriented programming, data is


more important than the data. more important than function.
Procedural Oriented Programming Object-Oriented Programming

Procedural programming is based on Object-oriented programming is based on


the unreal world. the real world.

Procedural programming is used for Object-oriented programming is used for


designing medium-sized programs. designing large and complex programs.

Procedural programming uses the concept Object-oriented programming uses the


of procedure abstraction. concept of data abstraction.

Code reusability absent in procedural Code reusability present in object-oriented


programming, programming.

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

Object Oriented Programming (OOP) is a style of programming that uses objects


to model real-world things like data and behavior. It focuses on key ideas
like inheritance, encapsulation, and polymorphism. The main goal of OOP is to
group data and the functions that work on it together, so that the data is protected
and can only be changed in controlled ways.

Characteristics of an Object-Oriented Programming Language


There are some basic concepts that act as the building blocks of OOPs i.e.
Class
In C++, the basic building block of Object-Oriented Programming is the class. A
class is a user-defined type that acts like a blueprint to create objects that share
similar properties (data) and behaviors (functions).
For example, you can define an Animal class with properties like name, age,
and species, and behaviors like eat(), sleep(), and makeSound().
A class is defined using the class keyword in C++.
class Animal {
public:
string species;
int age;
int name;

// Member functions
void eat() {
// eat something
}
void sleep() {
// sleep for few hrs
}
void makeSound () {
// make sound;
}
};
Here, public is the access specifier that specify what functions are available to
others.
Object
An object is a real, usable instance of a class that has specific properties and
behaviors. In C++, an object is created from a class.
For example, Animal is just an idea or blueprint, but a cat is a real object based
on that class. So, classes are concepts, and objects are the actual things created
from those concepts.
When you define a class, no memory is used. But when you create an object from
that class, memory is allocated for it. You can create an object like this:
#include <iostream>
using namespace std;

class Animal
{
public:
string species;
int age;
int name;

// Member functions
void eat()
{
// eat something
}
void sleep()
{
// sleep for few hrs
}
void makeSound()
{
// make sound;
}
};

int main()
{
Animal cat;
}
Objects take up space in memory and have an associated address like a record in
pascal or structure or union. When a program is executed, the objects interact by
sending messages to one another.
Encapsulation
In simple terms, encapsulation is defined as wrapping up data and information
under a single unit. In Object-Oriented Programming, encapsulation is defined as
binding together the data and the functions that manipulate them together in a
class. Consider an example of the Animal class, the data members species, age
and name are encapsulated with the member functions like eat(), sleep, etc. They
can be protected by the access specifier which hides the data of the class from
outside.

Abstraction
Abstraction is one of the most essential and important features of object-oriented
programming in C++. Abstraction means displaying only essential information and
ignoring the other details. Data abstraction refers to providing only essential
information about the data to the outside world, hiding the background details or
implementation.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerator will increase the speed of the car or applying brakes will
stop the car but he does not know how on pressing the accelerator the speed is
actually increasing, he does not know about the inner mechanism of the car or the
implementation of the accelerator, brakes, etc in the car. This is what abstraction
is.
Types of Abstraction:
1. Data abstraction - This type only shows the required information about the
data and ignores unnecessary details.
2. Control Abstraction - This type only shows the required information about the
implementation and ignores unnecessary details.

Abstraction using Access Specifiers


Access specifiers are the main pillar of implementing abstraction in C++. We can
use access specifiers to enforce restrictions on class members. For example:
 Members declared as public in a class can be accessed from anywhere in the
program.
 Members declared as private in a class, can be accessed only from within the
class. They are not allowed to be accessed from any part of the code outside
the class.

Polymorphism
The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of an entity to behave different in different
scenarios. person at the same time can have different characteristics.
For example, the same makeSound() method, the output will vary depending on
the type of animal. So, this is an example of polymorphism where the makeSound()
method behaves differently depending on the Animal type (Dog or Cat).

Inheritance
The capability of a class to derive properties and characteristics from another class
is called Inheritance. Inheritance is one of the most important features of Object-
Oriented Programming.
 Sub Class: The class that inherits properties from another class is called Sub
class or Derived Class.
 Super Class: The class whose properties are inherited by a sub-class is called
Base Class or Superclass.

Inheritance supports the concept of “reusability”, i.e. when we want to create a new
class and there is already a class that includes some of the code that we want, we
can derive our new class from the existing class. By doing this, we are reusing the
fields and methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Types of inheritance:
 Single Inheritance.
 Multiple Inheritance.
 Multilevel Inheritance.
 Hierarchical Inheritance.
 Hybrid Inheritance.

Dynamic Binding in C++

Dynamic binding in C++ is a practice of connecting the function calls with the
function definitions by avoiding the issues with static binding, which occurred at
build time. Because dynamic binding is flexible, it avoids the drawbacks of static
binding, which connected the function call and definition at build time.
In simple terms, Dynamic binding is the connection between the function
declaration and the function call.
Usage of Dynamic Binding
It is also possible to use dynamic binding with a single function name to handle
multiple objects. Debugging the code and errors is also made easier and
complexity is reduced with the help of Dynamic Binding.
Static Binding Vs Dynamic Binding
Static Binding Dynamic Binding

It takes place at compile time which is It takes place at runtime so it is referred to


referred to as early binding as late binding

Execution of static binding is faster than Execution of dynamic binding is slower


dynamic binding because of all the than static binding because the function
information needed to call a function. call is not resolved until runtime.

It takes place using normal function calls,


operator overloading, and function It takes place using virtual functions
overloading.

Real objects never use static binding Real objects use dynamic binding
MESSAGE PASSING
Message passing in C++ refers to the mechanism by which objects communicate
and interact with each other within an object-oriented program. It is a fundamental
concept in Object-Oriented Programming (OOP) and is typically achieved through
method or function calls.

How Message Passing Works in C++:


 Classes and Objects:
In C++, classes serve as blueprints for creating objects. Each object encapsulates data
(member variables) and functions (member methods) that operate on that data.
 Method Invocation:
When one object needs to interact with another, it does so by "sending a message" to the
target object. This message is essentially a request to invoke a specific method of the target
object.
 Information Exchange:
The "message" can also include information (arguments) that is passed to the invoked method,
allowing the calling object to provide data to the receiving object.
 Processing the Message:
The target object receives the message and executes the requested method. This method may
access or modify the object's internal state or perform other operations based on the received
information.

Example:
Consider a Car object and a Driver object. The Driver object might "send a
message" to the Car object to startEngine(). This involves the Driver object calling
the startEngine() method of the Car object.
#include <iostream>
class Car {
public:
void startEngine() {
std::cout << "Car engine started." << std::endl;
}
};
class Driver {
public:
void operateCar(Car& car) {
std::cout << "Driver is attempting to start the car." << std::endl;
car.startEngine(); // Message passing: Driver object invokes Car's startEngine
method
}
};
int main() {
Car myCar;
Driver myDriver;
myDriver.operateCar(myCar);
return 0;
}

Benefits of Message Passing:


 Encapsulation:
It supports encapsulation by allowing objects to interact without needing to know the internal
implementation details of other objects.
 Abstraction:
It promotes abstraction by focusing on what an object does rather than how it does it.
 Modularity and Flexibility:
It encourages a modular design, making programs easier to understand, maintain, and extend.
 Polymorphism:
It is integral to achieving polymorphism, where different objects can respond to the same
message in their own unique ways.
C++ Data Types
Data types specify the type of data that a variable 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 as 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.
Example:
#include <iostream>

using namespace std;

int main() {

// Creating a variable to store integer

int var = 10;

cout << var;

return 0;

Output
10
In the above code, we needed to store the value 10 in our program, so we created
a variable var. But before var, we have used the keyword 'int'. This keyword is
used to define that the variable var will store data of type integer.
Classification of Datatypes:

1. Character Data Type (char)


The character data type is used to store a single character. The keyword used to
define a character is char. Its size is 1 byte, and it stores characters enclosed in
single quotes (' '). It can generally store upto 256 characters according to
their ASCII codes.
Example:

#include <iostream>

using namespace std;

int main() {

// Character variable

char c = 'A';

cout << c;

return 0;

Output
A
2. Integer Data Type (int)
Integer data type denotes that the given variable can store the integer numbers.
The keyword used to define integers is int. Its size is 4-bytes (for 64-bit) systems
and can store numbers for binary, octal, decimal and hexadecimal base systems in
the range from -2,147,483,648 to 2,147,483,647.
Example:
#include <iostream>

using namespace std;

int main() {

// Creating an integer variable

int x = 25;

cout << x << endl;

// Using hexadecimal base value

x = 0x15;

cout << x;

return 0;

Output
25
21

3. Boolean Data Type (bool)


The boolean data type is used to store logical values: true(1) or false(0). The
keyword used to define a boolean variable is bool. Its size is 1 byte.
Example:

#include <iostream>

using namespace std;

int main() {
// Creating a boolean variable

bool isTrue = true;

cout << isTrue;

return 0;
}
Output
1

4. Floating Point Data Type (float)


Floating-point data type is used to store numbers with decimal points. The
keyword used to define floating-point numbers is float. Its size is 4 bytes (on 64-bit
systems) and can store values in the range from 1.2e-38 to 3.4e+38.
Example:

#include <iostream>

using namespace std;

int main() {

// Floating point variable with a decimal value

float f = 36.5;

cout << f;

return 0;
}
Output
36.5

5. Double Data Type (double)


The double data type is used to store decimal numbers with higher precision. The
keyword used to define double-precision floating-point numbers is double. Its size
is 8 bytes (on 64-bit systems) and can store the values in the range from 1.7e-
308 to 1.7e+308
Example:

#include <iostream>
using namespace std;

int main() {

// double precision floating point variable

double pi = 3.1415926535;

cout << pi;

return 0;
}
Output
3.14159

6. Void Data Type (void)


The void data type represents the absence of value. We cannot create a variable
of void type. It is used for pointer and functions that do not return any value using
the keyword void.

Operators in C++ are special symbols or keywords that perform specific operations
on one or more operands. They are fundamental building blocks for manipulating
data and controlling program flow. C++ provides a rich set of built-in operators,
which can be categorized into various types:

1. Arithmetic Operators: Perform mathematical calculations.


 + (Addition)

 - (Subtraction)

 * (Multiplication)

 / (Division)

 % (Modulus - remainder of division)

 ++ (Increment - increases value by 1)

 -- (Decrement - decreases value by 1)


2. Relational (Comparison) Operators: Compare two operands and return a boolean
result (true or false).
 == (Equal to)

 != (Not equal to)

 > (Greater than)

 < (Less than)


 >= (Greater than or equal to)

 <= (Less than or equal to)


3. Logical Operators: Combine or modify boolean expressions.
 && (Logical AND - true if both operands are true)

 || (Logical OR - true if at least one operand is true)

 ! (Logical NOT - inverts a boolean value)


4. Assignment Operators: Assign a value to a variable.
 = (Simple assignment)

 +=, -=, *=, /=, %= (Compound assignment operators)


5. Bitwise Operators: Perform operations on individual bits of integer operands.
 & (Bitwise AND)

 | (Bitwise OR)

 ^ (Bitwise XOR)

 ~ (Bitwise NOT/One's complement)

 << (Left shift)

 >> (Right shift)


6. Other Important Operators:
 sizeof (Returns the size of a variable or type)

 ?: (Ternary/Conditional operator)

 & (Address-of operator)

 * (Dereference operator)

 :: (Scope resolution operator)

 . (Member access operator)

 -> (Pointer member access operator)

 new, delete (Memory allocation/deallocation operators)

 static_cast, dynamic_cast, reinterpret_cast, const_cast (Type casting operators)


Operator Precedence and Associativity:
Operators have a defined order of evaluation (precedence) and a rule for evaluating
operators of the same precedence (associativity). Understanding these rules is
crucial for writing correct and predictable C++ code.

Operators in C++
C++ operators are the symbols that operate on values to perform specific
mathematical or logical computations on given values. They are the foundation of
any programming language.
Example:

#include <iostream>

using namespace std;

int main() {

int a = 10 + 20;

cout << a;

return 0;
}
Output
30
Here, '+' is an addition operator and does the addition of 10 and 20 operands
and return value 30 as a result.

C++ Operator Types


C++ operators are classified into 6 types on the basis of type of operation they
perform:
1. Arithmetic Operators
Arithmetic operators are used to perform arithmetic or mathematical operations
on the operands. For example, '+' is used for addition.
Name Symbol Description

Addition + Adds two operands.

Subtraction - Subtracts second operand from the first.

Multiplication * Multiplies two operands.

Division / Divides first operand by the second operand.


Name Symbol Description

Modulo Operation % Returns the remainder an integer division.

Increment ++ Increase the value of operand by 1.

Decrement -- Decrease the value of operand by 1.

#include <iostream>

using namespace std;

int main() {

int a = 8, b = 3;

// Addition

cout << "a + b = " << (a + b) << endl;

// Subtraction

cout << "a - b = " << (a - b) << endl;

// Multiplication

cout << "a * b = " << (a * b) << endl;

// Division

cout << "a / b = " << (a / b) << endl;

// Modulo

cout << "a % b = " << (a % b) << endl;

// Increament

cout << "++a = " << ++a << endl;

// Decrement
cout << "b-- = " << b--;

return 0;
}
Output
a + b = 11
a - b = 5
a * b = 24
a / b = 2
a % b = 2
++a = 9
--b = 2

Important Points:
 The Modulo operator (%) operator should only be used with integers. Other
operators can also be used with floating point values.
 ++a and a++, both are increment operators, however, both are slightly different.
In ++a, the value of the variable is incremented first and then it is used in the
program. In a++, the value of the variable is assigned first and then it is
incremented. Similarly happens for the decrement operator.
You may have noticed that some operator works on two operands while other work
on one. On the basis of this operators are also classified as:
 Unary: Works on single operand.
 Binary: Works on two operands.
 Ternary: Works on three operands.

2. Relational Operators
Relational operators are used for the comparison of the values of two operands.
For example, '>' check right operand is greater.
Name Symbol Description

Is Equal To == Checks both operands are equal

Checks first operand is greater than the second


>
Greater Than operand

Greater Than or >= Checks first operand is greater than equal to the
Name Symbol Description

Equal To second operand

Checks first operand is lesser than the second


<
Less Than operand

Less Than or Equal Checks first operand is lesser than equal to the
<=
To second operand

Not Equal To != Checks both operands are not equal

EXAMPLE:

#include <iostream>
using namespace std;

int main() {
int a = 6, b = 4;

// Equal operator
cout << "a == b is " << (a == b) << endl;

// Greater than operator


cout << "a > b is " << (a > b) << endl;

// Greater than Equal to operator


cout << "a >= b is " << (a >= b) << endl;

// Lesser than operator


cout << "a < b is " << (a < b) << endl;

// Lesser than Equal to operator


cout << "a <= b is " << (a <= b) << endl;

// Not equal to operator


cout << "a != b is " << (a != b);

return 0;
}
Output
a == b is 0
a > b is 1
a >= b is 1
a < b is 0
a <= b is 0
a != b is 1

3. Logical Operators
Logical operators are used to combine two or more conditions or constraints or to
complement the evaluation of the original condition in consideration. The result
returns a Boolean value, i.e., true or false.
Name Symbol Description

Logical AND && Returns true only if all the operands are true or non-zero.

Logical OR || Returns true if either of the operands is true or non-zero.

Logical NOT ! Returns true if the operand is false or zero.

4. Bitwise Operators
Bitwise operators are works on bit-level. So, compiler first converted to bit-level
and then the calculation is performed on the operands.
Name Symbol Description

Copies a bit to the evaluated result if it exists in both


&
Binary AND operands

Binary OR | Copies a bit to the evaluated result if it exists in any of the


Name Symbol Description

operand

Copies the bit to the evaluated result if it is present in


^
Binary XOR either of the operands but not both

Shifts the value to left by the number of bits specified by


<<
Left Shift the right operand.

Shifts the value to right by the number of bits specified by


>>
Right Shift the right operand.

One's
~ Changes binary digits 1 to 0 and 0 to 1
Complement

Note: Only char and int data types can be used with Bitwise Operators.

#include <iostream>

using namespace std;

int main() {

int a = 6, b = 4;

// Binary AND operator

cout << "a & b is " << (a & b) << endl;

// Binary OR operator

cout << "a | b is " << (a | b) << endl;


// Binary XOR operator

cout << "a ^ b is " << (a ^ b) << endl;

// Left Shift operator

cout << "a << 1 is " << (a << 1) << endl;

// Right Shift operator

cout << "a >> 1 is " << (a >> 1) << endl;

// One’s Complement operator

cout << "~(a) is " << ~(a);

return 0;

Output
a & b is 4
a | b is 6
a ^ b is 2
a<<1 is 12
a>>1 is 3
~(a) is -7

5. Assignment Operators
Assignment operators are used to assign value to a variable. We assign the
value of right operand into left operand according to which assignment operator we
use.
Name Symbol Description

Assigns the value on the right to the variable on the


Assignment = left.
Name Symbol Description

Add and First add right operand value into left operand then
Assignment += assign that value into left operand.

Subtract and First subtract right operand value into left operand
-=
Assignment then assign that value into left operand.

Multiply and First multiply right operand value into left operand
Assignment *= then assign that value into left operand.

Divide and First divide right operand value into left operand then
Assignment /= assign that value into left operand.

Example:
#include <iosteam>

using namespace std;

int main() {

int a = 6, b = 4;

// Assignment Operator.

cout << "a = " << a << endl;

// Add and Assignment Operator.

cout << "a += b is " << (a += b) << endl;

// Subtract and Assignment Operator.

cout << "a -= b is " << (a -= b) << endl;


// Multiply and Assignment Operator.

cout << "a *= b is " << (a *= b) << endl;

// Divide and Assignment Operator.

cout << "a /= b is " << (a /= b);

return 0;

Output
a = 6
a += b is 10
a -= b is 6
a *= b is 24
a /= b is 6

6. Ternary or Conditional Operators


Conditional operator returns the value, based on the condition. This operator
takes three operands, therefore it is known as a Ternary Operator.
Syntax:
Expression1 ? Expression2 : Expression3

In the above statement:


 The ternary operator ? determines the answer on the basis of the evaluation
of Expression1.
 If Expression1 is true, then Expression2 gets evaluated.
 If Expression1 is false, then Expression3 gets evaluated

#include <iostream>

using namespace std;

int main() {

int a = 3, b = 4;

// Conditional Operator
int result = (a < b) ? b : a;

cout << "The greatest number "

"is " << result;

return 0;

Output
The greatest number is 4

Miscellaneous Operators
Apart from these operators, there are a few operators that do not fit in any of the
above categories. These are:

1. sizeof Operator
sizeof operator is a unary operator used to compute the size of its operand or
variable in bytes. For example,
sizeof (char);
sizeof (var_name);

2. Comma Operator (,)


Comma operator is a binary operator that is used for multiple purposes. It is used
as a separator or used to evaluate its first operand and discards the result; it then
evaluates the second operand and returns this value (and type).
int n = (m+1, m-2, m+5);
int a, b, c;

3. Addressof Operator (&)


Addressof operator is used to find the memory address in which a particular
variable is stored. In C++, it is also used to create a reference.
&var_name;

4. Dot Operator(.)
Dot operator is used to access members of structure variables or class objects
using their object names.
obj . member;

5. Arrow Operator
Arrow operator is used to access the variables of classes or structures through its
pointer.
sptr -> member;
6. Casting Operators
Casting operators are used to convert the value of one data type to another data
type. For example, for an integer value x:
(float)x
static_cast<float>(x)

Operator Precedency and Associativity


When there are multiple operators in a single expression, operator precedency
and associativity decide in which order and which part of expression are
calculate. Precedency tells which part of expression should be calculate first and
associativity tells which direction to solve when same precedency operators are in
expression.

Operator Precedence
Operator precedence says which operation is calculate first in the expression when
expression have different precedency operators. For example:
3 * 2 + 8;
Will be evaluated as:
(3 * 2) + 8 = 14
It is because multiplication (*) have higher precedency then addition (+).

Operator Associativity
Operator associativity says if expression have more than one operator with same
precedence then calculation happen in right to left or left to right.
50 / 25 * 2 = 1
Will be evaluated as:
(50 / 25) * 2

You might also like