0% found this document useful (0 votes)
17 views54 pages

C++ New One

C++ is a versatile programming language that supports multiple paradigms, including object-oriented and procedural programming, making it suitable for a wide range of applications. It features a variety of data types, operators, and control structures, allowing for efficient and organized code development. The language promotes code reusability through functions and supports recursion for solving complex problems.

Uploaded by

behoh38682
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)
17 views54 pages

C++ New One

C++ is a versatile programming language that supports multiple paradigms, including object-oriented and procedural programming, making it suitable for a wide range of applications. It features a variety of data types, operators, and control structures, allowing for efficient and organized code development. The language promotes code reusability through functions and supports recursion for solving complex problems.

Uploaded by

behoh38682
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/ 54

C++

C++ is a powerful and versatile programming language


that combines features from different programming
paradigms. Here's a breakdown to get you started:
● General-purpose: C++ can be used to create a wide
variety of applications, from simple games to complex
operating systems.
● Object-oriented: C++ allows you to organize your
code using objects, which makes it easier to model
real-world entities and their behaviors. This leads to
cleaner, more maintainable code and readable code.
● Procedural: C++ also supports procedural
programming, which is a traditional approach where
you break down your program into a series of steps or
functions.
● High-performance: C++ provides a high level of
control over system resources and memory, making it
suitable for developing efficient programs that need to
run fast.
● Cross-platform: C++ code can be compiled and run
on different operating systems with minimal changes.
C++ was developed by Bjarne Stroustrup as an extension
of the C language. It incorporates the familiar syntax of C
while adding features like object-oriented programming
and better memory management.
Here are some of the reasons why C++ is a popular
choice for programmers:
● Speed and Efficiency: C++ code can run very fast,
making it ideal for performance-critical applications
like game development and scientific computing.
● Wide Range of Applications: C++ is used in various
domains, including systems programming, embedded
systems, game development, and more.
● Large Community and Resources: There's a vast
community of C++ programmers and a wealth of
learning resources available online and in libraries.
Variables
In C++, a variable is like a named box that you use to
store data within your program. It essentially acts as a
reserved space in memory where you can hold information
during program execution. Here's a closer look at
variables in C++:
What variables do:
● Store data: Variables can hold different types of data,
depending on what you need your program to work
with. This data can be numbers (whole or decimals),
characters, logical values (true or false), or even
references to more complex data structures.
● Change value: The beauty of variables is that their
contents are not fixed. You can modify the value
stored in a variable throughout your program using
assignment statements. This allows you to track
changing information or perform calculations.

Data types :
Data types in C++ are fundamental to how your program
stores and manipulates information. They define the type
of data a variable can hold, its size in memory, and the
operations you can perform on it. Here's a detailed
explanation of data types in C++:
Categories of Data Types:
C++ offers two main categories of data types:
1. Primitive Data Types (Fundamental Data Types):
○ These are the basic building blocks for storing
data.
○ They are predefined by the language and directly
supported by the hardware.
○ Common primitive data types include:
■ Integer types:
■ int: Stores whole numbers (e.g., 10,
-25). The size of int can vary
depending on the system (typically 2 or
4 bytes).
■ Other integer types like short, long,
and long long provide different
ranges of values and memory usage.
■ Floating-point types:
■ float and double: Store numbers with
decimals (e.g., 3.14, -12.98). float
typically uses 4 bytes of memory, while
double uses 8 bytes for higher
precision.
■ Character type:
■ char: Stores a single character (e.g.,
'a', '!', '$', ‘3’). Represented within single
quotes.
■ Boolean type:
■ bool: Represents logical values, either
true or false. Typically occupies 1
byte of memory.

2. Non-Primitive Data Types (User-Defined Data


Types):
○ These are more complex data structures created
by programmers to organize data in a specific
way.
○ They are built on top of primitive data types.
○ Examples include:
■ Arrays: Collections of elements of the same
data type, accessed using an index.
■ String : Collection of character.
■ Structures: User-defined groups of
variables of different data types under a
single name.
■ Unions: Variables that can hold different
data types at different times, but only one
value at a time. (Less commonly used)
■ Classes: Blueprints for creating objects,
which encapsulate data (member variables)
and behavior (member functions).
■ Enumerations (enums): User-defined data
types consisting of named integer constants.

Operators
C++ operators are symbols that perform operations on
variables or values. They are the building blocks of
expressions and play a crucial role in manipulating data
and controlling program flow.
1. Arithmetic Operators:

These operators perform basic mathematical calculations on numeric operands.

● + (Addition): Adds two operands.


int sum = 5 + 3; // sum will be 8
- (Subtraction): Subtracts the second operand from the first.
int difference = 10 - 4; // difference will be 6

* (Multiplication): Multiplies two operands.


int product = 7 * 2; // product will be 14
/ (Division): Divides the first operand by the second. Be cautious of integer division
and potential remainder.
float quotient = 15.0 / 3.0; // quotient will be 5.0
int result = 10 / 3; // result will be 3 (truncates decimal)
% (Modulus): Returns the remainder after division.
int remainder = 10 % 3; // remainder will be 1

2. Assignment Operators:

These operators assign values to variables.

= (Simple Assignment): Assigns the value of the right operand to the left operand.
int x = 10;
+=, -=, *=, /=, %= (Compound Assignment): Perform the operation specified by the
symbol and then assign the result to the left operand. Shortcut for combined operations.
int y = 5;
y += 3; // Equivalent to y = y + 3; (y will be 8)

3. Relational Operators:

These operators compare operands and return boolean values (true or false) based on
the comparison.

== (Equal to): Checks if two operands are equal.


bool areEqual = (5 == 3); // areEqual will be false
!= (Not Equal to): Checks if two operands are not equal.
bool notEqual = (10 != 10); // notEqual will be false
< (Less Than): Checks if the left operand is less than the right operand
bool isLess = (7 < 9); // isLess will be true
> (Greater Than): Checks if the left operand is greater than the right operand.
bool isGreater = (2 > 1); // isGreater will be true
<= (Less Than or Equal to): Checks if the left operand is less than or equal to the right
operand.
bool lessOrEqual = (4 <= 5); // lessOrEqual will be true
>= (Greater Than or Equal to): Checks if the left operand is greater than or equal to
the right operand.

bool greaterOrEqual = (8 >= 8); // greaterOrEqual will be true

4. Logical Operators:

These operators combine boolean expressions and return a single boolean value.

&& (Logical AND): Returns true only if both operands are true.

bool isEven = (10 % 2 == 0) && (10 > 5); // isEven will be true

|| (Logical OR): Returns true if at least one operand is true.

bool isEligible = (age >= 18) || (hasExperience); // isEligible


will be true if either condition is met

! (Logical NOT): Inverts the logical state of the operand (true becomes false, false
becomes true).
bool isNegative = !(number > 0); // isNegative will be true if
number is not positive

5. Bitwise Operators (continued):

& (Bitwise AND): Performs bitwise AND on corresponding bits of two operands. The
result is 1 only if both bits at that position are 1. Otherwise, the result is 0.

int a = 5 (binary: 0101);


int b = 3 (binary: 0011);

int result = a & b; // result will be 1 (binary: 0001)

| (Bitwise OR): Performs bitwise OR on corresponding bits. The result is 1 if at least


one of the bits at that position is 1.

int a = 5 (binary: 0101);


int b = 3 (binary: 0011);

int result = a | b; // result will be 7 (binary: 0111)

^ (Bitwise XOR): Performs bitwise XOR on corresponding bits. The result is 1 if the bits
at that position are different.

int a = 5 (binary: 0101);


int b = 3 (binary: 0011);

int result = a ^ b; // result will be 6 (binary: 0110)

~ (Bitwise NOT): Inverts all bits of the operand (1 becomes 0, 0 becomes 1).

int number = 8 (binary: 1000);

int inverted = ~number; // inverted will be -9 (binary: 1111,


two's complement representation)

6. Increment and Decrement Operators:

● ++ (Increment): Increments the value of the operand by 1 (prefix or postfix).


○ Prefix ++: Increments the operand and then returns the new value.
○ Postfix ++: Returns the current value of the operand and then increments
it.
● -- (Decrement): Decrements the value of the operand by 1 (prefix or postfix,
similar behavior to increment)

7. Conditional (Ternary) Operator:

A shorthand way to write an if-else statement in a single line.

int grade = 85;

string result = (grade >= 90) ? "Excellent" : "Good";

Conditional Statement
Conditional statements are fundamental building blocks in
C++ that allow your program to make decisions based on
certain conditions. They control the flow of execution by
directing the program to execute different code sections
depending on whether a condition is true or false. Here's a
detailed explanation of conditional statements in C++ with
examples:
Types of Conditional Statements:

C++ offers several conditional statements to handle various decision-making scenarios:

1. if statement:
○ The most basic conditional statement.
○ Syntax:

if (condition) {
// code to execute if condition is true

○ }
○ Example:
○ int age = 20;
○ if (age >= 18) {
○ std::cout << "You are eligible to vote." <<
std::endl;
○ }

if-else statement:

● Provides an alternative block of code to execute if the condition in the if


statement is false.
● Syntax:

if (condition) {

// code to execute if condition is true

} else {

// code to execute if condition is false

● }

Example:

char initial = 'A';

if (initial >= 'a' && initial <= 'z') {

std::cout << initial << " is a lowercase letter."


<< std::endl;

} else {

std << initial << " is an uppercase letter or not


an alphabet." << std::endl;

if-else if ladder:

● Used for handling multiple conditions sequentially.


● Checks conditions one by one. If a condition is true, the corresponding code
block is executed, and the rest of the else if and else blocks are skipped.

if (condition1) {
// code to execute if condition1 is true

} else if (condition2) {

// code to execute if condition1 is false and condition2 is true

} else {

// code to execute if all conditions are false

Example:

int score = 80;

if (score >= 90) {

std::cout << "Excellent!";

} else if (score >= 80) {

std::cout << "Good job!";

} else if (score >= 60) {

std::cout << "You passed.";

} else {

std::cout << "Study harder next time.";

Switch Statement
The switch statement in C++ is a multi-way branching
statement that allows you to execute different code blocks
based on the value of a single expression. It's a powerful
tool for handling choices with a limited set of possible
values. Here's a detailed explanation with examples:

switch (expression) {
case value1:
// code to execute if expression equals value1
break;
case value2:
// code to execute if expression equals value2
break;
// ... more cases for other possible values
default:
// code to execute if expression doesn't match any case value
(optional)
break;
}

Example :
char grade = 'B';

switch (grade) {
case 'A':
std::cout << "Excellent work!" << std::endl;
break;
case 'B':
std::cout << "Good job!" << std::endl;
break;
case 'C':
std::cout << "You can do better." << std::endl;
break;
default:
std::cout << "Invalid grade." << std::endl;
}

Loop statement
C++ offers three primary loop constructs that enable you
to execute a block of code repeatedly until a certain
condition is met. These loops are essential for automating
repetitive tasks and iterating through collections of data.
Here's a detailed explanation of each loop type with
examples:
1. for loop:
● The most versatile loop for iterating a predetermined
number of times.
● Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed repeatedly
}
for (int i = 1; i <= 5; i++) {
std::cout << i << " ";
}

2. while loop:
● A loop that continues executing as long as a specified
condition remains true.
● Syntax:
while (condition) {
// code to be executed repeatedly
// (update expression can be included within the loop body)
}

int number = 1;
while (number <= 10) {
std::cout << number << " ";
number++;
}

3. do-while loop:

● Similar to a while loop, but the code block is


guaranteed to execute at least once, even if the condition
is initially false.
● Syntax:
do {
// code to be executed repeatedly
// (update expression can be included within the loop body)
} while (condition);

int number = 0;
do {
std::cout << number << " ";
number++;
} while (number < 3);

Functions :
Functions are fundamental building blocks in C++ that
promote code reusability, modularity, and organization.
They encapsulate a specific task or set of instructions that
can be invoked from different parts of your program.
Here's a detailed explanation of functions in C++ with
examples:
Function Definition:
● A function definition specifies the function's name,
return type (if it returns a value), parameters (optional
inputs), and the code block that defines its
functionality.
● Syntax:
return_type function_name(parameter1_type
parameter1_name, parameter2_type parameter2_name, ...)
{
// code to be executed when the function is called
}

double calculateArea(double length, double width) {


return length * width;
}
// Function call (passing values to calculate area)
int main() {
double rect_length = 5.0;
double rect_width = 3.0;
double area = calculateArea(rect_length,
rect_width);
std::cout << "Area of the rectangle: " << area <<
std::endl;
return 0;
}

Recursion Function
In C++, recursion refers to a function that calls itself within
its own definition. It's a powerful technique for solving
problems that can be broken down into smaller
subproblems of the same type. Here's a detailed
explanation of recursion functions with examples:
Concept:
● A recursive function has a base case, which is a
simple condition that stops the recursion and provides
a direct solution.
● The recursive case involves calling the function itself
with a modified version of the original problem
(usually a smaller version).
● The function calls keep happening until the base case
is reached, at which point the return values from each
function call start propagating back up, ultimately
providing the solution to the original problem.
void function_name(parameter) {
// Base case (stops the recursion)
if (condition) {
// Handle the base case and return a value
} else {
// Recursive case (call the function itself with a
modified parameter)
function_name(modified_parameter);
}
}

int factorial(int n) {
if (n == 0) { // Base case: factorial of 0 is 1
return 1;
} else {
// Recursive case: factorial(n) = n *
factorial(n-1)
return n * factorial(n - 1);
}
}

int main() {
int num = 5;
int result = factorial(num);
std::cout << "Factorial of " << num << " is: " <<
result << std::endl;
return 0;
}
Arrays
Arrays in C++ are powerful data structures that allow you to
store a collection of elements of the same data type under a
single variable name. They provide a way to efficiently
manage and access related data items. Here's a detailed
explanation of arrays in C++ with examples:
Declaring and Initializing Arrays:

● Arrays are declared by specifying the data type, array name, and size enclosed
in square brackets [].
● The size indicates the number of elements the array can hold.
// Syntax 1: Declaration without initialization
int numbers[5]; // Array to hold 5 integers

// Syntax 2: Initialization during declaration


double temperatures[4] = {22.5, 18.2, 25.1, 19.8}; // Array with initial values

Accessing Elements:

● Individual elements are accessed using the array name followed by an index
within square brackets.
● Indexing starts from 0, so the first element has index 0, the second element has
index 1, and so on.
numbers[2] = 10; // Assigning value 10 to the third element (index 2)
std::cout << temperatures[0] << std::endl; // Printing the first element (value
at index 0)

Iterating Through Arrays:

● You can use loops like for or while to iterate through all elements of the array
for (int i = 0; i < 5; i++) {
std::cout << numbers[i] << " "; // Accessing and printing each element
}

Multidimensional Arrays:

● C++ supports multidimensional arrays, allowing you to create grids or tables of


data.
● Declaration involves specifying multiple sizes within square brackets.
int matrix[2][3]; // A 2x3 matrix to hold integers

std::string students[3] = {"Alice", "Bob", "Charlie"};


int grades[3][2]; // Array to store grades for 3 students in 2 subjects

grades[0][0] = 90; // Alice's grade in subject 1


grades[1][1] = 85; // Bob's grade in subject 2

// Accessing and printing elements using nested loops for a 2D array


for (int i = 0; i < 3; i++) {
std::cout << students[i] << ": ";
for (int j = 0; j < 2; j++) {
std::cout << grades[i][j] << " ";
}
std::cout << std::endl;
}

Pointers :
Pointers in C++ are variables that store memory addresses as their values. They are
used to manipulate memory and facilitate dynamic memory allocation, among other
tasks. Understanding pointers is crucial for advanced memory management, efficient
data structures, and accessing hardware directly.

1. Declaration and Initialization:


int x = 10;
int* ptr; // Declaring a pointer
ptr = &x; // Initializing pointer with address of x

● int* ptr; declares a pointer named ptr that can store the memory address of
an integer.
● ptr = &x; assigns the memory address of variable x to the pointer ptr.

2. Dereferencing:

int y = *ptr; // Dereferencing ptr to get the value at its memory address

*ptr is used to access the value stored at the memory address pointed to by ptr.

3. Pointer Arithmetic:
int arr[5] = {1, 2, 3, 4, 5};
int* arrPtr = arr; // Pointer to the first element of arr

// Accessing array elements using pointer arithmetic


cout << *(arrPtr + 2); // Outputs: 3

*(arrPtr + 2) accesses the value at an offset of 2 positions from the memory address
pointed to by arrPtr.

4. Dynamic Memory Allocation:


int* dynamicPtr = new int; // Allocating memory dynamically
*dynamicPtr = 20; // Assigning a value to the dynamically allocated memory
delete dynamicPtr; // Freeing the dynamically allocated memory

● new int; allocates memory dynamically on the heap for an integer.


● delete dynamicPtr; deallocates the memory allocated by new, preventing
memory leaks.
5. Pointers and Functions:
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int m = 5, n = 10;
swap(&m, &n);
cout << "m: " << m << ", n: " << n; // Outputs: m: 10, n: 5
return 0;
}

Passing pointers to functions allows them to modify variables outside their scope.

6. Null Pointers:
int* nullPtr = nullptr; // Initializing a pointer with a null value

7. Pointers and Arrays:


int arr[3] = {10, 20, 30};
int* ptrArr = arr;

cout << *ptrArr; // Outputs: 10


cout << *(ptrArr + 1); // Outputs: 20
Access Modifiers :
In C++, access modifiers are keywords used to control the
accessibility of class members (variables and functions)
from outside the class. They specify the level of access
that other parts of the program have to the members of a
class. C++ provides three main access modifiers: public,
private, and protected.

Public Access Modifier:

● Members declared as public are accessible from


outside the class through objects of the class.
● Public members can be accessed by any part of the
program, including other classes and functions.
class MyClass {

public:

int publicVar;

void publicFunc() {

// Code

};

Private Access Modifier:


● Members declared as private are accessible only
from within the class itself. They cannot be accessed
from outside the class or through objects of the class.
● Private members are hidden from the outside world,
providing encapsulation and data hiding.
class MyClass {

private:

int privateVar;

int privateFunc() {

// Code

};

Protected Access Modifier:

● Members declared as protected are accessible


within the class itself and by derived classes.
● Protected members provide a level of access between
public and private, allowing derived classes to
access them but not other parts of the program.

class A {
protected:

String name;

void protectedFunc() {

// Code

};

class B : public A {

public:

void modifyBaseMember() {

name = “shivam”;// Accessing protected member of


base class

};
OOP Concept

Object-Oriented Programming (OOP) is a programming


paradigm that focuses on organizing code into objects,
which bundle data (attributes or properties) and methods
(functions or procedures) that operate on that data. C++ is
a powerful object-oriented programming language that
supports OOP concepts such as encapsulation,
inheritance, polymorphism, and abstraction.

Object :

In C++, an object is like a real-world thing that we


want to represent in our program. Think of it as a
box that holds related data (called attributes or
variables) and functions (called methods) that
operate on that data.

For example, imagine you want to represent a car in


a program. You would create an object called Car.
Inside the Car object, you could store data like the
car’s color, brand, and speed, and define functions
to make the car start or stop.
Here’s a simple analogy:
● Object: A specific car (e.g., a red Toyota).
● Attributes (data): The color is red, the brand is
Toyota, the speed is 60 mph.
● Methods (functions): Actions like starting the
engine or stopping.

// Class (blueprint)
class Car {
public:
string color;
string brand;
int speed;

void start() {
cout << "Car started" << endl;
}
void stop() {
cout << "Car stopped" << endl;
}
};

// Creating an object from the class


int main() {
Car myCar; // Object 'myCar' of type 'Car'
myCar.color = "Red"; // Setting attributes
myCar.brand = "Toyota";
myCar.speed = 60;

myCar.start(); // Using the start method


myCar.stop(); // Using the stop method

return 0;
}
Class :

In C++, a class is a blueprint for creating objects. It defines


the structure and behavior of objects of that type. A class
encapsulates data (attributes or properties) and methods
(functions or procedures) that operate on that data. An
object, on the other hand, is an instance of a class. It
represents a specific entity based on the class blueprint.
class ClassName {
private:
// Data members (attributes or properties)

public:
// Constructor(s)
ClassName() {
// Initialization code
}

// Member function(s) (methods or behaviors)


};

Constructor
A constructor in C++ is a special member function that
gets called automatically when an object of a class is
created. It initializes the object's data members or
performs any other necessary setup operations.
Constructors have the same name as the class and do not
have a return type, not even void. They can be overloaded,
allowing multiple constructors with different parameter
lists within the same class.

Here are the types of constructors in C++:

1. Default Constructor:

A default constructor is a constructor with no parameters


or parameters that have default values. If no constructor is
explicitly defined for a class, the compiler generates a
default constructor automatically. Its purpose is to
initialize the object's data members to default values.
class MyClass {
public:
// Default constructor
MyClass() {
// Initialization code
}
};

2. Parameterized Constructor:
A parameterized constructor accepts parameters to
initialize the object's data members with values provided
during object creation. It allows customization of object
initialization based on user-defined values.
class Point {
private:
int x, y;

public:
// Parameterized constructor
Point(int a, int b) {
// Initialization code
}
};

3. Copy Constructor:

A copy constructor is a constructor that initializes an


object using another object of the same class. It creates a
copy of the existing object, allowing the creation of an
independent object with the same state.
class MyClass {
private:
int data;

public:
// Copy constructor
MyClass(const MyClass& gh) {
data = gh.data;
// Copying other data members if needed
}
};

4. Inline Constructor : In C++, an inline constructor is a


constructor that is defined inside the class itself, instead of
being defined outside the class. When a constructor is
inline, it tells the compiler to replace the function call with
the actual code of the constructor, which can make things
faster for small functions.

#include <iostream>

class Person {
public:
std::string name;
int age;

// Inline constructor defined inside the


class
Person(std::string n, int a) : name(n),
age(a) {

}
};

int main() {
Person p1("John", 25);
std::cout << "Name: " << p1.name << ", Age: "
<< p1.age << std::endl;
}

This Pointer :
In C++, the this pointer is a special pointer available inside
every non-static member function of a class. It points to
the object for which the member function is called. In
simple terms, it refers to the current object.
Imagine each object of a class is a person, and each
person has a name tag to identify themselves. When an
object (person) calls a function (does something), this is
like the name tag they use to refer to themselves.

#include <iostream>
using namespace std;

class Person {
public:
string name;

// Constructor to initialize the name


Person(string name) {
// The 'this' pointer is used to distinguish between
the
// class member 'name' and the parameter 'name'.
this->name = name;
}

// Function to display the person's name


void display() {
cout << "My name is: " << this->name << endl;
}
};

int main() {
// Creating an object of Person
Person person1("Alice");

// Calling display function


person1.display(); // Output: My name is: Alice

return 0;
}

Destructor :
In C++, a destructor is a special member function of a
class that is automatically called when an object of that
class goes out of scope or is explicitly deleted. The
primary purpose of a destructor is to release resources
acquired by the object during its lifetime, such as
dynamically allocated memory or other system resources.

Syntax of a Destructor:
class ClassName {
public:
// Constructor(s)
ClassName() {
// Initialization code
}

// Destructor
~ClassName() {
// Cleanup code
}
};

Example :
#include <iostream>
using namespace std;

class MyClass {
public:
// Constructor
MyClass() {
cout << "Constructor called" << endl;
}

// Destructor
~MyClass() {
cout << "Destructor called" << endl;
}
};

int main() {
MyClass obj; // Object created
MyClass obj2;
// Object goes out of scope after this block
return 0;
}

Types of Destructors in C++:

Default Destructor:
● If a class does not have a user-defined destructor, the
compiler provides a default destructor.
● The default destructor does not release any resources
explicitly allocated by the object.
Example:
class MyClass {
public:
// No user-defined destructor
};
User-Defined Destructor:
● A destructor explicitly defined by the programmer to
release resources held by the object.
● Useful for releasing dynamically allocated memory,
closing files, or releasing any other acquired
resources.
class FileHandler {
private:
FILE* file;

public:
// Constructor
FileHandler(const char* filename) {
file = fopen(filename, "w");
}

// Destructor
~FileHandler() {
fclose(file);
}
};

Friend Function :
In C++, a friend function is a special function that is not a
member of a class, but it can still access the private and
protected members of the class. Think of it like a trusted
friend who is allowed to see and interact with the private
details of an object, even though they’re not part of that
object's inner circle (class).
#include <iostream>
using namespace std;

class Box {
private:
int length; // private data

public:
// Constructor to initialize length
Box(int l) : length(l) {}

// Declaring a friend function


friend void printLength(Box b);
};

// Friend function definition


void printLength(Box b) {
// Accessing private member 'length'
cout << "Length of the box: " << b.length << endl;
}

int main() {
// Creating an object of Box
Box myBox(10);

// Calling the friend function


printLength(myBox); // Output: Length of the box:
10

return 0;
}
Encapsulation :
Encapsulation is one of the fundamental principles of
object-oriented programming (OOP) and is often described
as bundling data and methods that operate on the data
into a single unit, typically a class. It involves hiding the
internal state of an object and requiring all interaction with
the object to occur through well-defined interfaces. This
helps in achieving data hiding, abstraction, and modularity,
making the code easier to understand, maintain, and
reuse.

#include <iostream>
using namespace std;
class Rectangle {
private:
double length;
double width;

public:
// Setter methods
void setLength(double len) {
if (len >= 0)
length = len;
else
cout << "Invalid length\n";
}

void setWidth(double wid) {


if (wid >= 0)
width = wid;
else
cout << "Invalid width\n";
}

// Getter methods
double getLength() const {
return length;
}

double getWidth() const {


return width;
}

// Method to calculate area


double calculateArea() const {
return length * width;
}
};

int main() {
Rectangle rect;
// Setting length and width using setter methods
rect.setLength(5.0);
rect.setWidth(4.0);

// Getting length and width using getter methods


cout << "Length: " << rect.getLength() << endl;
cout << "Width: " << rect.getWidth() << endl;

// Calculating area
cout << "Area: " << rect.calculateArea() << endl;

return 0;
}

Inheritance :
Inheritance is a key concept in object-oriented
programming (OOP) that allows a class to inherit
properties and behavior from another class. It promotes
code reusability and facilitates the creation of a hierarchy
of classes, where subclasses inherit attributes and
methods from their parent class(es), also known as base
class(es) or superclass(es).

In C++, inheritance is implemented using the class


keyword along with a colon (:) followed by the access
specifier (public, protected, or private) and the
name of the base class(es). There are different types of
inheritance, including
single inheritance,
multiple inheritance,
hierarchical inheritance,
multilevel inheritance, and
hybrid inheritance.
#include <iostream>
using namespace std;

// Base class
class Shape {
protected:
double width;
double height;

public:
Shape(double w, double h) : width(w), height(h) {}

void setWidth(double w) {
width = w;
}

void setHeight(double h) {
height = h;
}
};

// Derived class
class Rectangle : public Shape {
public:
Rectangle(double w, double h) : Shape(w, h) {}

double area() {
return width * height;
}
};
int main() {
Rectangle rect(5.0, 4.0);
cout << "Area of rectangle: " << rect.area() <<
endl;

return 0;
}

Single Inheritance:
● Single inheritance involves one base class and one
derived class.
● In this type of inheritance, the derived class inherits
the members (both data members and member
functions) of the base class.
class Base {
public:
void display() {
cout << "Base class\n";
}
};

class Derived : public Base {


public:
void show() {
cout << "Derived class\n";
}
};

int main() {
Derived obj;
obj.display(); // Accessing base class member
obj.show(); // Accessing derived class member
return 0;
}

Multiple Inheritance:
● Multiple inheritance involves a derived class inheriting
from more than one base class.
● In this type of inheritance, the derived class inherits
members from all the base classes
class Base1 {
public:
void display1() {
cout << "Base1 class\n";
}
};

class Base2 {
public:
void display2() {
cout << "Base2 class\n";
}
};

class Derived : public Base1, public Base2 {


public:
void show() {
cout << "Derived class\n";
}
};

int main() {
Derived obj;
obj.display1(); // Accessing Base1 member
obj.display2(); // Accessing Base2 member
obj.show(); // Accessing Derived member
return 0;
}

Hierarchical Inheritance:
● Hierarchical inheritance involves one base class and
multiple derived classes.
● In this type of inheritance, multiple classes are derived
from a single base class.
class Base {
public:
void display() {
cout << "Base class\n";
}
};

class Derived1 : public Base {


public:
void show1() {
cout << "Derived1 class\n";
}
};

class Derived2 : public Base {


public:
void show2() {
cout << "Derived2 class\n";
}
};

int main() {
Derived1 obj1;
obj1.display(); // Accessing base class member
obj1.show1(); // Accessing derived class member

Derived2 obj2;
obj2.display(); // Accessing base class member
obj2.show2(); // Accessing derived class member

return 0;
}

Multilevel Inheritance:
● Multilevel inheritance involves a chain of inheritance
where a derived class is derived from another derived
class.
● In this type of inheritance, a class is derived from
another derived class, forming a multilevel hierarchy.
class Base {
public:
void display() {
cout << "Base class\n";
}
};

class Derived1 : public Base {


public:
void show1() {
cout << "Derived1 class\n";
}
};

class Derived2 : public Derived1 {


public:
void show2() {
cout << "Derived2 class\n";
}
};

int main() {
Derived2 obj;
obj.display(); // Accessing base class member
obj.show1(); // Accessing derived class member
obj.show2(); // Accessing derived class member

return 0;
}

Hybrid Inheritance:
● Hybrid inheritance involves a combination of multiple
types of inheritance.
● In this type of inheritance, a class is derived from
more than one base class, and the inheritance
hierarchy is a combination of multiple types of
inheritance.
class Base1 {
public:
void display1() {
cout << "Base1 class\n";
}
};

class Base2 {
public:
void display2() {
cout << "Base2 class\n";
}
};

class Derived1 : public Base1 {


public:
void show1() {
cout << "Derived1 class\n";
}
};

class Derived2 : public Base1, public Base2 {


public:
void show2() {
cout << "Derived2 class\n";
}
};

int main() {
Derived2 obj;
obj.display1(); // Accessing Base1 member
obj.display2(); // Accessing Base2 member
obj.show2(); // Accessing Derived2 member

return 0;
}
Polymorphism :

Polymorphism is a fundamental concept in object-oriented


programming (OOP) that allows objects to be treated as
instances of their parent class, even when they are
instances of a subclass. Polymorphism enables the same
interface to be used for objects of different classes,
promoting code flexibility and reusability.

There are two main types of polymorphism in C++:


compile-time polymorphism (also known as static
polymorphism) and runtime polymorphism (also known as
dynamic polymorphism).

Compile-time Polymorphism:
● Compile-time polymorphism is achieved through
function overloading and operator overloading.
● Function overloading allows multiple functions
with the same name but different parameter lists
to be defined within the same scope.
● Operator overloading enables operators to be
overloaded so that they can be used with
user-defined types.
● Example of function overloading:
#include <iostream>
using namespace std;

class Calculator {
public:
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
};

int main() {
Calculator calc;
cout << "Integer sum: " << calc.add(3, 4) << endl;
cout << "Double sum: " << calc.add(3.5, 4.7) <<
endl;
return 0;
}

Operator Overloading :
Operator overloading in C++ allows you to redefine the
behavior of operators (like +, -, *, etc.) for user-defined
types (like classes). This means you can use operators
with objects in a way that makes sense for your program.

In everyday life, the + operator usually means adding two


numbers, like 2 + 3 = 5. But what if you wanted to "add"
two custom objects, like two books? Operator overloading
lets you decide what "adding" means in that context, for
example, combining the pages of both.

#include <iostream>
using namespace std;

class Box {
public:
int length;

// Constructor to initialize length


Box(int l) : length(l) {}

// Overloading the + operator


Box operator+(const Box& b) {
// Create a new Box object with the combined
length
Box newBox(0);
newBox.length = this->length + b.length;
return newBox;
}
};

int main() {
// Creating two Box objects
Box box1(10);
Box box2(20);

// Using the overloaded + operator


Box box3 = box1 + box2;

cout << "Combined length of box1 and box2: " <<


box3.length << endl; // Output: 30
return 0;
}

Runtime Polymorphism:

● Runtime polymorphism is achieved through function


overriding and virtual functions.

Function overriding occurs when a derived class provides


a specific implementation of a method that is already
defined in its base class.
#include <iostream>

using namespace std;

// Base class

class Animal {

public:

// Function in base class (no virtual keyword)

void sound() {

cout << "Animals make sound." << endl;


}

};

// Derived class

class Dog : public Animal {

public:

// Overriding the sound() function in the derived


class

void sound() {

cout << "Dog barks." << endl;

};

int main() {

// Base class object

Animal animal;

animal.sound(); // Output: Animals make sound.

// Derived class object

Dog dog;

dog.sound(); // Output: Dog barks.


// Base class pointer pointing to derived class
object

Animal* animalPtr = &dog;

animalPtr->sound(); // Output: Animals make sound


(not Dog barks)

return 0;

Virtual functions are functions declared in a base class


with the virtual keyword, which can be overridden by
derived classes.
#include <iostream>
using namespace std;

class Animal {
public:
virtual void makeSound() {
cout << "Animal makes a sound\n";
}
};

class Dog : public Animal {


public:
void makeSound() {
cout << "Dog barks\n";
}
};

class Cat : public Animal {


public:
void makeSound() override {
cout << "Cat meows\n";
}
};

int main() {
Animal *animal1 = new Dog();
Animal *animal2 = new Cat();

animal1->makeSound(); // Calls Dog's makeSound()


animal2->makeSound(); // Calls Cat's makeSound()

delete animal1;
delete animal2;
return 0;
}

Enum :
An enum (short for "enumeration") in C++ is a user-defined
type that consists of a set of named integer constants. It’s like
creating a custom list of options that are more readable and
understandable.

Think of an enum as a list of labels for a set of related values.


For example, if you want to represent days of the week,
instead of using numbers like 0 for Sunday or 1 for Monday,
you can use an enum to give these numbers meaningful
names like SUNDAY, MONDAY, etc.
enum EnumName {value1, value2, value3, ... };

#include <iostream>
using namespace std;

enum Day {
SUNDAY, // 0
MONDAY, // 1
TUESDAY, // 2
WEDNESDAY, // 3
THURSDAY, // 4
FRIDAY, // 5
SATURDAY // 6
};

int main() {
Day today = WEDNESDAY;

// Output the current day


if (today == WEDNESDAY) {
cout << "Today is Wednesday." << endl;
}

return 0;
}

Declaring the enum: We create an enum called Day that lists the days of
the week.
Assigning values: Each day is given a number automatically, starting from
0. So SUNDAY is 0, MONDAY is 1, and so on.
Using the enum: We set today to WEDNESDAY and then check if today is
Wednesday. If it is, it prints "Today is Wednesday."
Why use an enum?

● Readability: It’s easier to understand and work with meaningful


names like MONDAY rather than raw numbers like 1.
● Maintainability: If you need to add or remove options, you can easily
update the enum list without having to remember or change the
numbers.

Custom Values :
enum Month {
JANUARY = 1, // starts from 1
FEBRUARY, // 2
MARCH, // 3
APRIL = 10, // custom value 10
MAY // 11 (continues from 10)
};

Generics :
Generics in C++ are primarily implemented using
templates. Templates allow you to write generic and
reusable code by defining functions, classes, and data
structures to work with any data type. This is achieved
by parameterizing types, which means that you can write a
function or a class without specifying the exact data type
it operates on until the code is actually used. Here's a
detailed explanation with examples:
#include <iostream>
using namespace std;

template <typename T>


T add(T a, T b) {
return a + b;
}

int main() {
cout << add<int>(2, 3) << endl; // Outputs: 5
cout << add<double>(2.5, 3.1) << endl; // Outputs: 5.6
return 0;
}

You might also like