C++ New One
C++ New One
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.
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:
2. Assignment Operators:
= (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.
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 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
& (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.
^ (Bitwise XOR): Performs bitwise XOR on corresponding bits. The result is 1 if the bits
at that position are different.
~ (Bitwise NOT): Inverts all bits of the operand (1 becomes 0, 0 becomes 1).
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:
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:
if (condition) {
} else {
● }
Example:
} else {
if-else if ladder:
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
} else {
Example:
} else {
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:
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
}
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
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)
● 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:
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.
● 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
*(arrPtr + 2) accesses the value at an offset of 2 positions from the memory address
pointed to by arrPtr.
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
public:
int publicVar;
void publicFunc() {
// Code
};
private:
int privateVar;
int privateFunc() {
// Code
};
class A {
protected:
String name;
void protectedFunc() {
// Code
};
class B : public A {
public:
void modifyBaseMember() {
};
OOP Concept
Object :
// Class (blueprint)
class Car {
public:
string color;
string brand;
int speed;
void start() {
cout << "Car started" << endl;
}
void stop() {
cout << "Car stopped" << endl;
}
};
return 0;
}
Class :
public:
// Constructor(s)
ClassName() {
// Initialization code
}
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.
1. Default Constructor:
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:
public:
// Copy constructor
MyClass(const MyClass& gh) {
data = gh.data;
// Copying other data members if needed
}
};
#include <iostream>
class Person {
public:
std::string name;
int age;
}
};
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;
int main() {
// Creating an object of Person
Person person1("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;
}
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) {}
int main() {
// Creating an object of Box
Box myBox(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";
}
// Getter methods
double getLength() const {
return length;
}
int main() {
Rectangle rect;
// Setting length and width using setter methods
rect.setLength(5.0);
rect.setWidth(4.0);
// 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).
// 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";
}
};
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";
}
};
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";
}
};
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";
}
};
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";
}
};
int main() {
Derived2 obj;
obj.display1(); // Accessing Base1 member
obj.display2(); // Accessing Base2 member
obj.show2(); // Accessing Derived2 member
return 0;
}
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;
}
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.
#include <iostream>
using namespace std;
class Box {
public:
int length;
int main() {
// Creating two Box objects
Box box1(10);
Box box2(20);
Runtime Polymorphism:
// Base class
class Animal {
public:
void sound() {
};
// Derived class
public:
void sound() {
};
int main() {
Animal animal;
Dog dog;
return 0;
class Animal {
public:
virtual void makeSound() {
cout << "Animal makes a sound\n";
}
};
int main() {
Animal *animal1 = new Dog();
Animal *animal2 = new Cat();
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.
#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;
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?
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;
int main() {
cout << add<int>(2, 3) << endl; // Outputs: 5
cout << add<double>(2.5, 3.1) << endl; // Outputs: 5.6
return 0;
}