0% found this document useful (0 votes)
3 views27 pages

Unit 1 (Programming in c++)

This document provides an overview of C++ programming fundamentals, including the character set, identifiers, keywords, data types, operators, and control statements. It covers variable declaration, dynamic initialization, memory management, and input/output operations using <iostream> and <iomanip>. Additionally, it explains the compilation and execution process, debugging, and common control structures like loops and conditional statements.

Uploaded by

dashtanmay292008
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)
3 views27 pages

Unit 1 (Programming in c++)

This document provides an overview of C++ programming fundamentals, including the character set, identifiers, keywords, data types, operators, and control statements. It covers variable declaration, dynamic initialization, memory management, and input/output operations using <iostream> and <iomanip>. Additionally, it explains the compilation and execution process, debugging, and common control structures like loops and conditional statements.

Uploaded by

dashtanmay292008
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/ 27

UNIT 1 (PROGRAMMING IN C++)

C++ Fundamentals
C++ character set
The term "C++ character set" refers to the characters and symbols that the C++ program can comprehend and
accept. The character set basically consists of combining some mathematical symbols, such as the Digits and Special
symbols, with the Alphabets and White Spaces of the English language.

Sr.no Category Character


ABCDEFGHIJKLMNOPQRSTUVWXYZ
1. Alphabets
abcdefghijklmnopqrstuvwxyz
2. Digits 0123456789
3. Special characters - * / A () [] {} = <>. ' " $ , ; : % ! & ? _ (underscore) # @
4. White spaces Space bar (Blank space), Horizontal Tab, newline, backspace

Identifiers and Keywords


Keywords- Keywords are predefined words/reserved words that have special meanings to the compiler.
Example: int money, char name[50] => Here int and char are keywords.

Identifiers- Identifiers are the unique names given to variables, classes, functions, or other entities by the
programmer.
Example: int money, char name[50] => Here money and name are Identifiers.

Rules for naming identifiers


• Identifiers can be composed of letters, digits, and the underscore character.
• It has no limit on name length.
• It must begin with either a letter or an underscore.
• It is case-sensitive.
• We cannot use keywords as identifiers.

Data Types
int:
The integer datatype in C is used to store the integer numbers.
Size: Typically, 4 bytes (depends on the system).

float:
It is used to store decimal numbers with single precision. Can have max 7 numbers after decimal point
Size: Typically, 4 bytes.

char:
Character data type allows its variable to store only a single character.
Size: Typically, 1 byte.

double:
It is used to store decimal numbers with double precision. Can have 14 numbers after a decimal point.
Size: Typically, 8 bytes.

void:
It does not provide a result value to its caller. It is used to represent nothing.

Qualifiers
short:
Used for small integers.
Size: Typically, 2 bytes (but this can vary by system).
Example: short num = 10;
long:
Used for large integers.
Size: Typically, 4 bytes for long and 8 bytes for long long on most systems.
Example: long distance = 1000000000;

signed:
Can only store both positive and negative integers. Used for integers
Size: 4 bytes
Example: signed int balance = -100;

unsigned:
Can only store positive integers.
Size: 4 bytes
Example: unsigned int count = 50;

const:
Specifies that a variable’s value cannot be changed after it is initialized. It makes the value constant during the
program’s execution.
Example: const int maxLimit = 100;

Constants
Integer Constants:
Integer constants are whole numbers (both positive and negative) without any decimal points.
Example: const int x = 100; // 100 is an integer constant

Floating Point Constants:


These constants represent real numbers, i.e., numbers that contain decimal points.
Example:
const float pi = 3.14f; // 'f' specifies it's a float constant
const double e = 2.71828; // Double precision floating-point constant

Character Constants:
Represent single characters enclosed in single quotes (' ').
Example: const char letter = 'A’; // 'A' is a character constant

String Constants:
These are sequences of characters enclosed in double quotes (" ").
Example: const char greeting[] = "Hello, World!"; // String constant

Enumeration Constants (Enum Constants):


Enumeration constants are a set of named values that belong to a group. These are used when you have multiple
related options to choose from.

Example: enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
enum Day today = Wednesday; // 'Wednesday' is an enum constant
By default, SUNDAY = 0, MONDAY = 1, and so on.
enum Day { Sunday = 1, Monday, Tuesday = 10 };

Symbolic Constants:
Symbolic constants are values assigned a name using #define or the const keyword. Values defined using this cannot
be changed.
Example: #define PI 3.14159

Escape Sequence
\b (Backspace) - Moves the cursor one place backward.
\t (Horizontal tab) - Inserts some whitespace to the left of the cursor.
\n (New line) - Moves the cursor to the start of the next line.
\v (Vertical tab) - Inserts vertical space, moves the cursor downwards (if supported by the system).
\a (Alert/Bell) - Produces a beep sound (if supported by the system).
\f (Form Feed) - Moves to the next page (if supported by the system).
\r (Carriage Return) - Moves the cursor to the start of the line (overwrites existing text) (if supported by the system).
\0 (Null Character) - represents the end of a string in C-style strings.
Variables and Declaration
A variable is used to store values. And before using a variable, you must declare it by specifying its datatype.
Example: int age = 25; // Declares a variable 'age' type integer and assigns the value 25 to 'age'

Dynamic Initialization of Variables


Dynamic Initialization means assigning a value to a variable at runtime instead of during declaration.
Example: int a = 10, b = 20;
int sum = a + b; // sum is initialized dynamically at runtime

Reference Variables
A reference variable is like an alternative name for an existing variable. It doesn't create a new variable but gives
another name to an existing one.

Example: int x = 10;


int &y = x; // 'y' is a reference to 'x'
y = 20; // Changing 'y' also changes 'x'

Operators and Expressions

Unary Operators
Unary operators are operators that work on a single operand

Unary Minus (-)


This operator is used to change the sign of a number. Positive becomes negative and Negative becomes positive

int a = 10;
int b = -a; // Unary minus applied, now b is -10

int a = -10;
int b = -a; // Unary minus applied, now b is 10

Increment (++)
Adds 1 to a variable.
++x (Pre-increment) → First increase, then use the value.
x++ (Post-increment) → First use the value, then increase.

Decrement (--)
Subtracts 1 from a variable.
--x (Pre-decrement) → First decrease, then use the value.
x-- (Post-decrement) → First use the value, then decrease.

Logical NOT (!)


This operator flips a boolean value:

!true → false
!false → true

sizeof() Operator
This operator tells you the size (in bytes) of a variable or data type.

sizeof(int);

Typecasting (Type Conversion)


Typecasting is used to convert one data type into another. Two types of Typecasting Implicit Typecasting and Explicit
Typecasting.

int x = 10; double pi = 3.14;

double y = x; // Implicit conversion (int → double)


int approx = (int) pi; // Explicit typecast (double → int)
Arithmetic Operators: Arithmetic operators perform basic mathematical operations like addition,
subtraction, multiplication, division, and modulus.

Addition (+) This operator adds two numbers.


Subtraction (-) This operator subtracts one number from another.
Multiplication (*) This operator multiplies two numbers.
Division (/) This operator divides one number by another.
Modulus (%) The modulus operator (%) returns the remainder after division.

Relational Operators: Relational operators compare two values and return a Boolean result (true or false).
They help in decision-making. These operators return true (1) or false (0).

Less Than (<) Checks if the left value is smaller than the right value.
Less Than or Equal To (<=) Checks if the left value is smaller than OR equal to the right value.
Greater Than (>) Checks if the left value is greater than the right value.
Greater Than or Equal To (>=) Checks if the left value is greater than OR equal to the right value.

Equality Operators: These operators are used to compare values and return true or false.

== (Equal to) → Checks if two values are equal.


!= (Not equal to) → Checks if two values are not equal.

Logical Operators: Used to combine multiple conditions.


&& (Logical AND) → Returns true only if both conditions are true.
|| (Logical OR) → Returns true if at least one condition is true.

Conditional Operator (?): An alternative for if-else.


(condition)? value_if_true : value_if_false;

Example:
int min = (x < y)? x : y; // If x < y, return x, else return y

Assignment Operators
Operator Meaning Example
= Assigns a value A = 5;
+= Adds and assigns a += 2; (same as a = a + 2)
-= Subracts and assigns a -= 2; (same as a = a - 2)
*= Multiplies and assigns a *= 2; (same as a = a * 2)
/= Divides and assigns a /= 2; (same as a = a / 2)
%= Modulus and assigns a %= 2; (same as a = a % 2)

Scope Resolution Operator (::) Used to access global variables or class members when they are hidden by
local variables.

Memory Management Operators


new Used to allocate memory dynamically and delete Used to free memory dynamically.

Example:
int* ptr = new int; // Allocates memory for an integer
int* arr = new int[10]; // Allocate memory for an array of 10 integers
delete ptr; // Frees the allocated memory
delete[] arr; // Deallocate memory for the array of integers

Operator Precedence & Associativity


Precedence determines which operator is evaluated first.
Associativity decides the direction when multiple operators have the same precedence.

Operator Associativity Example


*/% Left to Right 10 / 2 * 3 → 15
+- Left to Right 5+3-2→6
= Right to Left x = y = 10; (Assign 10 to both)
Data Input and Output
What is <iostream.h>?
<iostream> header file is used in C++ to handle input and output (I/O), such as reading data from the user and
displaying output on the screen. It includes the same functions but follows Standard C++ rules.

Using cin and cout with Insertion (<<) and Extraction (>>)
cout (Output) Uses << (Insertion Operator)
cout is used to display output on the screen. The insertion operator (<<) sends data to cout.

Example:
cout << "Hello, World!"; // Output: Hello, World!

cin (Input) Uses >> (Extraction Operator)


cin is used to take user input. The extraction operator (>>) extracts data from the user and stores it in a variable.
You can take multiple inputs in one line using multiple >> operators.

Example:
Int age
cout << "Enter your age: ";
cin >> age; // Takes user input and stores it in 'age'

int a, b;
cout << "Enter two numbers: ";
cin >> a >> b; // Takes two inputs

Manipulators: Manipulators help format output by adjusting spaces, decimal precision, alignment, etc.

What is <iomanip>?
<iomanip> (I/O Manipulators Header) allows us to control output formatting like width, precision, and alignment in
cout output.

1. setw(n) – Set Width (Sets a fixed width for the output).

Example: cout << setw(10) << "Hello" << setw(10) << "World";

Output: Hello World

2. endl – New Line (Moves the output to a new line (same as \n)). Also flushes the output buffer.

Example: cout << "Hello" << endl << "World";

Output: Hello
World

3. setprecision(n) – Control Decimal Points

Example: double pi = 3.14159265;


cout << setprecision(3) << pi;

Output: 3.14

4. setfill(c) – Fills empty spaces with a specified character. Works with setw().

Example: cout << setfill('*') << setw(10) << "Hi";

Output: ********Hi

5. setiosflags – Set Output Formatting, used to set formatting for output.

6. resetiosflags – Reset Formatting, Removes formatting set by setiosflags().


Flags

ios::left – Left-aligns the output in setw().

Example: cout << left << setw(10) << "Hi";

Output: Hi

ios::right – Right-aligns the output (default behavior).

Example: cout << right << setw(10) << "Hi";

Output: Hi

ios::scientific – Displays numbers in scientific notation.

Example: double num = 12345.6789;


cout << scientific << num;

Output: 1.234568e+04

ios::fixed – Displays floating-point numbers in a normal decimal format (not scientific).

Example: double pi = 3.14159;


cout << fixed << setprecision(2) << pi;

Output: 3.14

ios::showpos – Show Positive Sign (+), Forces cout to show + before positive numbers.

Example: cout << showpos << 10;

Output: +10

ios::showpoint – Show Decimal Point, Ensures decimal points are always shown. Even if no decimal part exists.

Example: cout << showpoint << fixed << setprecision(0) << 10.0;

Output: 10. /10.00

ios::unitbuf – Auto Flush Output Buffer. Automatically flushes cout after every output operation.

Example: cout << unitbuf;

Use of an Editor
An editor is a tool which is used to write and edit your C++ code.
Popular C++ Editors: Code::Blocks, Turbo C++ ,Notepad++, Dev-C++, Visual Studio Code (VS Code)

Basic command in c++ editors


New File - Create a new file
Open File - Open an existing .cpp file
Save File - Save the current file
Undo/ Redo - Undo/ Redo last action
Copy/ Cut - Copy/ Cut selected text
Paste - Paste copied text
Find - Search for text in the file
Replace - Replace text in the file
Compile - Convert code into machine language
Run (Execute) - Run the program
Compilation, Linking & Execution Process
Steps in Running a C++ Program
Writing Code: You write a .cpp file in an editor.
Compilation: The compiler checks for errors and converts code into machine language.
Linking: The linker combines different parts (like libraries) to create an executable file.
Execution: The final program (.exe file on Windows) runs and gives output.

Compile Code Using g++ (GCC Compiler)


g++ program.cpp -o program
Linking Process- Linking combines multiple files and libraries.
g++ file1.cpp file2.cpp -o output

Execution Process
./program # Linux/Mac
program.exe # Windows

Debugging: Debugging means finding and fixing errors (bugs) in the code.
Types of Errors:
Syntax Errors → Mistakes in code structure (e.g., missing ;)
Runtime Errors → Errors that happen while running the program (e.g., division by zero).
Logical Errors → Wrong output due to incorrect logic.

Control Statements
If-Else Statement: The if-else statement is used to execute code only if a condition is true.

if (condition) {
// Code executes if the condition is true
} else {
// Code executes if the condition is false
}

if (condition) {
// Code executes if the condition is true
} elseif (condition) {
// Code executes if the condition is true
}else {
// Code executes if the conditions are false
}

While Loop: The while loop repeats a block of code as long as the condition is true.

while (condition) {
// Code runs repeatedly until the condition becomes false
}

Do-While Loop: The do-while loop executes the block at least once, even if the condition is false.

do {
// Code executes at least once
} while (condition);

For Loop: The for loop is used when we know how many times we want to execute a loop.

for (initialization; condition; increment/decrement) {


// Code runs in a loop
}

Break Statement: The break statement stops a loop or switch statement immediately.
Continue Statement: The continue statement skips the rest of the loop body and moves to the next iteration.
Switch Statement: The switch statement checks multiple conditions using a case.

switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case matches
}

Comma Operator (,): The comma , operator executes multiple expressions in a single statement.

Example:
#include <iostream>
using namespace std;

int main() {
for (int i = 0, j = 5; i < 5; i++, j--) {
cout << "i: " << i << ", j: " << j << endl;
}
return 0;
}

Functions in Programming
Definition: A function is a self-contained block of code that performs a specific task. It helps in code reusability,
modularity, and readability.

Concept of Functions: Functions break a large program into smaller, manageable parts. They take input
(parameters), process it, and return output. Functions can be user-defined or built-in.

General Form of a Function

Syntax:
return_type function_name(parameters) {
// function body
return value; // (if applicable)
}
Example:
int add(int a, int b) {
return a + b;
}

Function Declaration (Prototype): The function declaration, also known as the function prototype, informs the
compiler about the function's name, return type, and parameters, without providing the actual body of the function.
It usually appears before the main() function.

Syntax:
return_type function_name(parameter_list);

Example:
int add(int, int); // Function prototype

Function Definition: The function definition provides the actual body of the function, specifying the code that
will run when the function is called.

Scope of a Variable: Scope refers to the region where a variable is accessible.


Local Scope: A variable declared inside a function is accessible only within that function.
Global Scope: A variable declared outside all functions is accessible throughout the program.
Local Variables: Declared inside a function or conditional statements. Accessible only within that function or
conditional statements. Memory is allocated to local variables when the function is called and deallocated when the
function ends or the conditional statements is executed.

Global Variables: Declared outside all functions. Accessible to all functions in the program.Retains its value
throughout the program's execution.

Function Call: A function call is when you use a function's name and pass any required arguments to execute the
function's code.

In C++, when calling a function, arguments can be passed in three ways, each method determines whether changes
inside the function affect the original variable.:

1. Pass by Value (Copy of the Variable)


When a function is called using call by value, A copy of each argument is created and passed to the function. The
function works with these copies rather than the actual variables. Any changes made to these copies do not affect
the original values of the arguments in the caller.

Example:
#include <iostream>
using namespace std;

void modify(int x) {
x = x + 10; // Only the local copy of x changes
cout << "Inside function: x = " << x << endl;
}

int main() {
int a = 5;
modify(a); // Passing a COPY of a
cout << "Outside function: a = " << a << endl; // Original 'a' remains unchanged
return 0;
}

Output:
Inside function: x = 15
Outside function: a = 5

2. Pass by Reference using Pointers


Instead of passing a copy to the function, we pass the address of the variable using a pointer (*). The function works
with the original variables, so changes made inside the function do affect the original variable.

Example:
#include <iostream>
using namespace std;

void modify(int *x) {


*x = *x + 10; // Dereferencing (*x) modifies the actual variable
cout << "Inside function: x = " << *x << endl;
}

int main() {
int a = 5;
modify(&a); // Passing the ADDRESS of 'a' using '&'
cout << "Outside function: a = " << a << endl; // 'a' gets modified
return 0;
}

Output:
Inside function: x = 15
Outside function: a = 15

3. Pass by Reference using Reference Variables (C++ Only)


Uses a reference variable (&) as an alias for the original variable. More readable and safer than pointers. Changes
inside the function do affect the original variable.
Example:
#include <iostream>
using namespace std;

void modify(int &x) {


x = x + 10; // Directly modifies the original variable
cout << "Inside function: x = " << x << endl;
}

int main() {
int a = 5;
modify(a); // Passing variable as a reference
cout << "Outside function: a = " << a << endl; // 'a' gets modified
return 0;
}

Output: Inside function: x = 15


Outside function: a = 15

Calling Function with Arrays as Parameters


When passing an array to a function, we are actually passing the base address of the array. The function modifies
the original array.

Example:
#include <iostream>
using namespace std;

void modifyArray(int arr[], int size) {


for (int i = 0; i < size; i++) {
arr[i] += 10; // Modifying array elements
}
}

int main() {
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);

modifyArray(numbers, size); // Passing array to function

cout << "Modified array: ";


for (int i = 0; i < size; i++) {
cout << numbers[i] << " "; // The original array is changed
}
return 0;
}

Output: Modified array: 11 12 13 14 15

Return by Reference: Instead of returning a copy, a function can return a reference to a variable.
This allows modifications to affect the original variable.

Example:
#include <iostream>
using namespace std;

int& getMax(int &x, int &y) {


return (x > y) ? x : y; // Returns reference to larger value
}

int main() {
int a = 10, b = 20;
getMax(a, b) = 50; // Modifies the larger value
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
Output: a = 10, b = 50

Inline Functions: The compiler replaces the function call with the function's body during compilation. Useful for
small functions and this makes execution faster..

Example:
#include <iostream>
using namespace std;

inline int add(int a, int b) {


return a + b; // The function is replaced directly in the code
}

int main() {
cout << "Sum: " << add(5, 3) << endl;
cout << "Sum: " << add(10, 7) << endl;
return 0;
}

Output: Sum: 8
Sum: 17

Functions with Default Parameters: We can set default values for parameters. If a function call does not
provide values, the default values are used.

Example:
#include <iostream>
using namespace std;

void greet(string name = "Guest") {


cout << "Hello, " << name << "!" << endl;
}

int main() {
greet(); // Uses default value "Guest"
greet("Alice"); // Uses provided value "Alice"
return 0;
}

Output:
Hello, Guest!
Hello, Alice!

Function Overloading: Function overloading allows multiple functions with the same name but different
parameters. The compiler decides which function to call based on the arguments.

Example:
#include <iostream>
using namespace std;

void print(int x) {
cout << "Integer: " << x << endl;
}

void print(double x) {
cout << "Double: " << x << endl;
}

void print(string x) {
cout << "String: " << x << endl;
}

void print(int x, double z) {


cout << "X: " << x << " Z :" <<z <<endl;
}
int main() {
print(10); // Calls print(int)
print(5.5); // Calls print(double)
print("Hello"); // Calls print(string)
print(5, 5.5); // Calls print(string)

return 0;
}

Output:
Integer: 10 Double: 5.5 String: Hello X: 5 Z: 5.5

Built-in Functions:

String functions like strlen(), strcpy(), strcmp(), and strcat() are functions from the <string.h>/< cstring > library
strlen() — Find the Length of a String The strlen() function is used to find the length of a string.
strcpy() — Copy a String The strcpy() function copies one string into another.
strcmp() — Compare Two Strings The strcmp() function compares two strings.
strcat() — Concatenate Two Strings The strcat() function concatenates (appends) one string to the end of another.

Example:
#include <iostream>
#include <cstring> // For string functions
using namespace std;

int main() {
char str1[20] = "Hello"; char str2[20] = "World";

cout << "Length of str1: " << strlen(str1) << endl; // strlen()

strcat(str1, str2); // strcat()


cout << "Concatenated string: " << str1 << endl;

strcpy(str1, "New"); // strcpy()


cout << "After strcpy: " << str1 << endl;

cout << "Comparing 'New' and 'World': " << strcmp(str1, str2) << endl; // strcmp()

return 0;
}

Output:
Length of str1: 5
Concatenated string: HelloWorld
After strcpy: New
Comparing 'New' and 'World': -1 (or other number negative number)

Mathematical functions like log(), log10(), pow(), sqrt(), sin(), cos(), and abs() are part of the <math.h> library.
log(x) - Returns the natural logarithm of x (base e)
log10(x) - Returns logarithm of x (base 10)
pow(x, y) - Returns x raised to the power y
sqrt(x)- Returns the square root of x
sin(x) - Returns the sine of x (radians)
cos(x) - Returns the cosine of x (radians)
abs(x) - Returns the absolute value of x

Example:
#include <iostream>
#include <math.h> // For math functions
using namespace std;

int main() {
cout << "log(10): " << log(10) <<”, log10(100): " << log10(100) <<”, pow(2, 3): " << pow(2, 3) <<”,” ;
cout << "sqrt(16): " << sqrt(16) <<”, sin(90 degrees): " << sin(90 * 3.14159 / 180) <<”,” ;
cout << "cos(0 degrees): " << cos(0) <<”,” ;
cout << "abs(-5): " << abs(-5) ;

return 0;
}

Output:
log(10): 2.30258, log10(100): 2, pow(2, 3): 8, sqrt(16): 4, sin(90 degrees): 1, cos(0 degrees): 1, abs(-5): 5

Character functions like isalnum(), isdigit(), islower(), isupper(), isalpha(), toupper(), and tolower() are part of the
<ctype.h> / <cctype> library.

isalnum(c)- Checks if c is a letter or digit


isdigit(c)- Checks if c is a digit
islower(c)- Checks if c is a lowercase letter
isupper(c)- Checks if c is an uppercase letter
tolower(c)- Converts c to lowercase
toupper(c)- Converts c to uppercase
isalpha(c)- Checks if c is an alphabet letter
isspace(c)- Checks if c is a whitespace (space, tab, newline)

Input/Output Functions fgets(), puts(), getchar(), putchar() are part of the <cstdio>/ <stdio.h> library.

fgets(str, size, stdin)- Reads a string


puts(str)- Prints a string
getchar()- Reads a single character
putchar(c)- Prints a single character

Example:
#include <iostream>
#include <cstdio> // For gets(), puts(), getchar(), putchar()
using namespace std;

int main() {
char str[50]; char ch;

cout << "Enter a string: ";


fgets(str, sizeof(str), stdin); // Reads entire line

cout << "You entered: ";


puts(str); // Prints string

cout << "Enter a character: ";


ch = getchar(); // Reads single character
cout << "You entered: ";
putchar(ch); // Prints single character

return 0;
}
These functions clrscr(), getch() are part of the <conio.h> library.

clrscr() Clears the screen (only in Turbo C++)


getch() Waits for a key press without displaying it

In modern C++, use system("CLS") instead of clrscr(), and cin.get() instead of getch().

Basic concepts of Object-Oriented Programming:


Definition: Object-Oriented Programming (OOP) is a programming approach that organizes code into objects and
classes. It focuses on real-world entities like students, cars, or banks instead of just logic and functions.

Benefits of OOP:
Modular Code – Code is divided into classes and objects.
Reusability – Code can be reused using inheritance.
Data Security – Data is hidden using encapsulation.
Easier Maintenance – Code is structured, making it easy to manage.
Objects and Classes:
Class: A blueprint for creating objects (e.g., a "Car" class).
Object: A specific instance of a class (e.g., "Toyota" is an object of "Car" class).

Example of Class and Object:


#include <iostream>
using namespace std;

// Defining a class
class Car {
public:
string brand; // Attribute
int speed; // Attribute

void display() { // Method (Function)


cout << "Car brand: " << brand << ", Speed: " << speed << " km/h" << endl;
}
};

int main() {
Car myCar; // Creating an object
myCar.brand = "Toyota";
myCar.speed = 120;

myCar.display(); // Calling method

return 0;
}

Output:
Car brand: Toyota, Speed: 120 km/h

Data Abstraction: Abstraction means hiding unnecessary details and showing only the essential features.
Example: A car has a steering wheel, but we don't need to know how the engine works to drive it.

Example:
#include <iostream>
using namespace std;

class ATM {
private:
int pin; // Hidden data (cannot be accessed directly)

public:
void setPin(int p) { pin = p; } // Only way to set pin
void showMessage() { cout << "Welcome to ATM!" << endl; }
};
int main() {
ATM myATM;
myATM.setPin(1234); // User sets pin
myATM.showMessage(); // Only the essential feature is shown
return 0;
}

Output: Welcome to ATM!


Data Encapsulation: Encapsulation means binding data and functions together into a single unit (class). Data is kept
private and can only be accessed through public methods.

Example:
#include <iostream>
using namespace std;

class BankAccount {
private:
double balance; // Private data (cannot be accessed directly)

public:
void deposit(double amount) { balance += amount; }
void showBalance() { cout << "Balance: $" << balance << endl; }
};

int main() {
BankAccount myAccount;
myAccount.deposit(500); // Data modified through method
myAccount.showBalance(); // Display balance

return 0;
}

Output:
Balance: $500

Inheritance: Inheritance allows a class to reuse properties of another class. The child class (derived class) inherits
from the parent class (base class).

Example:
#include <iostream>
using namespace std;

// Base class
class Animal {
public:
void eat() { cout << "I can eat!" << endl; }
};

// Derived class
class Dog : public Animal {
public:
void bark() { cout << "I can bark!" << endl; }
};

int main() {
Dog myDog;
myDog.eat(); // Inherited from Animal
myDog.bark(); // Defined in Dog class

return 0;
}

Output:
I can eat!
I can bark!
Polymorphism: Polymorphism means "many forms." A function or method behaves differently based on the object
calling it. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one
form.

Types of Polymorphism

Compile-time Polymorphism: This type of polymorphism is achieved by function overloading or operator


overloading.

Function Overloading: When there are multiple functions with the same name but different parameters.

Operator Overloading: C++ has the ability to provide the operators with a special meaning for a data type, this
ability is known as operator overloading. For example, we can make use of the addition operator (+) for string class
to concatenate two strings.

Runtime Polymorphism: This type of polymorphism is achieved by Function Overriding.

Example:
#include <iostream>
using namespace std;

// Base class
class Animal {
public:
virtual void makeSound() { cout << "Animal makes a sound!" << endl; }
};

// Derived class
class Dog : public Animal {
public:
void makeSound() override { cout << "Dog barks!" << endl; }
};

int main() {
Animal* myAnimal;
Dog myDog;
myAnimal = &myDog;
myAnimal->makeSound(); // Calls overridden method in Dog class

return 0;
}

Output:
Dog barks!

Classes and Objects:


Class: A class is a blueprint or template for creating objects. It defines variables (data members) and functions
(member functions) that describe the behavior of an object.

Object: An object is an instance of a class. It is created using the class definition and can access the data members
and member functions.

Declaration of a Class: A class is declared using the class keyword.

Example:
class Car {
public:
string brand;
int year;
};
Defining Member Functions Inside the Class:
class Car {
public:
string brand; int year;

void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};

Outside the Class: Functions can also be defined outside the class using the scope resolution operator (::).
class Car {
public:
string brand;
int year;

void display(); // Function declaration


};

// Function definition outside the class


void Car::display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}

Creating Objects

Example:
int main() {
Car myCar; // Creating an object
myCar.brand = "Toyota";
myCar.year = 2022;

myCar.display(); // Calling member function


return 0;
}

Accessing Class Members: Using the Dot Operator (.)

myCar.brand = "Toyota"; // Accessing and modifying data members


cout << myCar.brand; // Accessing and printing data

Array of Objects

Example:
class Car {
public:
string brand;
int year;
};

int main() {
Car cars[2]; // Array of objects

cars[0].brand = "Honda";
cars[0].year = 2018;

cars[1].brand = "Ford";
cars[1].year = 2020;

cout << "Car 1: " << cars[0].brand << ", " << cars[0].year << endl;
cout << "Car 2: " << cars[1].brand << ", " << cars[1].year << endl;

return 0;
}
Objects as Function Arguments

Example:
class Car {
public:
string brand;
int year;

void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};

// Function that takes object as argument


void showCar(Car c) {
c.display();
}

int main() {
Car myCar;
myCar.brand = "Tesla";
myCar.year = 2023;

showCar(myCar); // Passing object to function


return 0;
}

Functions Returning Objects

Example:
class Car {
public:
string brand; int year;

void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};

// Function returning an object


Car createCar() {
Car c;
c.brand = "BMW";
c.year = 2021;
return c; // Returning object
}

int main() {
Car myCar = createCar(); // Storing returned object
myCar.display(); // Calling function
return 0;
}

Constructors and Destructors


Constructor Definition: A constructor is a special member function in C++ that initializes objects of a class. It has
the same name as the class and is automatically called when an object is created.

Characteristics of a Constructor: Same name as the class, No return type (not even void), Automatically
invoked when an object is created, Can be overloaded (multiple constructors with different parameters), Can have
default arguments

Default Constructor: A default constructor is a constructor that takes no parameters. It initializes object data
with default values.
Example:
#include <iostream>
using namespace std;

class Car {
public:
string brand; int year;

// Default Constructor
Car() {
brand = "Unknown";
year = 0;
}

void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};

int main() {
Car myCar; // Default constructor is called
myCar.display();
return 0;
}

Output:
Brand: Unknown, Year: 0

Constructor with Default Arguments: A constructor can have default arguments, allowing us to pass fewer
arguments when creating an object.

Example:
#include <iostream>
using namespace std;

class Car {
public:
string brand; int year;

// Constructor with Default Arguments


Car(string b = "Toyota", int y = 2020) {
brand = b;
year = y;
}

void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};

int main() {
Car car1; // Uses default values
Car car2("Honda"); // Uses default year
Car car3("Ford", 2022);

car1.display();
car2.display();
car3.display();
return 0;
}

Output:
Brand: Toyota, Year: 2020
Brand: Honda, Year: 2020
Brand: Ford, Year: 2022
Parameterized Constructor: A parameterized constructor takes arguments to initialize an object with specific values.

EXAMPLE: Example (Explicit & Implicit Call)


#include <iostream>
using namespace std;

class Car {
public:
string brand; int year;

// Parameterized Constructor
Car(string b, int y) {
brand = b;
year = y;
}

void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};

int main() {
Car car1("Tesla", 2023); // Implicit call
Car car2 = Car("BMW", 2021); // Explicit call
car1.display();
car2.display();
return 0;
}

Output: Brand: Tesla, Year: 2023


Brand: BMW, Year: 2021

Constructor Overloading: We can define multiple constructors with different parameters (overloading).

EXAMPLE:
#include <iostream>
using namespace std;

class Car {
public:
string brand; int year;

// Default Constructor
Car() {
brand = "Unknown";
year = 0;
}

// Parameterized Constructor
Car(string b, int y) {
brand = b;
year = y;
}

void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};

int main() {
Car car1; // Calls default constructor
Car car2("Audi", 2022); // Calls parameterized constructor
car1.display();
car2.display();
return 0;
}
Copy Constructor: A copy constructor creates a new object by copying an existing object.

EXAMPLE:
#include <iostream>
using namespace std;

class Car {
public:
string brand; int year;

// Parameterized Constructor
Car(string b, int y) {
brand = b;
year = y;
}

// Copy Constructor
Car(const Car &c) {
brand = c.brand;
year = c.year;
}

void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};

int main() {
Car car1("Mercedes", 2023);
Car car2 = car1; // Copy constructor is called

car1.display();
car2.display();
return 0;
}

Dynamic Constructor: A dynamic constructor allocates memory dynamically using new.

EXAMPLE:
#include <iostream>
using namespace std;

class Car {
public:
string *brand;

// Constructor
Car(string b) {
brand = new string(b); // Dynamic memory allocation
}

void display() {
cout << "Brand: " << *brand << endl;
}

// Destructor to free memory


~Car() {
delete brand;
}
};

int main() {
Car car1("Lamborghini");
car1.display();
return 0;
}
Dynamic Initialization of Objects: Objects can be dynamically initialized at runtime using a constructor.

EXAMPLE:
#include <iostream>
using namespace std;

class Car {
public:
string brand;
int year;

// Parameterized Constructor
Car(string b, int y) {
brand = b;
year = y;
}

void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};

int main() {
string b; int y;

cout << "Enter car brand and year: ";


cin >> b >> y;

Car car(b, y); // Dynamic initialization


car.display();
return 0;
}

Destructor: A destructor is a special member function that is automatically called when an object is destroyed. It
cleans up resources allocated by an object.

Characteristics of Destructor: Same name as the class, but preceded by ~ (tilde), No return type and no parameters,
automatically invoked when an object goes out of scope, Only one destructor per class (cannot be overloaded)

Example:
#include <iostream>
using namespace std;

class Car {
public:
Car() {
cout << "Car created!" << endl;
}

~Car() {
cout << "Car destroyed!" << endl;
}
};

int main() {
Car myCar; // Constructor is called
return 0; // Destructor is called automatically
}

Inheritance:
Inheritance is a fundamental concept that enables a new class to inherit properties (attributes and methods) from
an existing class. This relationship allows for the reuse and extension of code, creating a hierarchy of classes that can
share and build upon each other’s functionality.
Key Concepts of Inheritance
• Base (or Parent) Class: The base class (also known as the parent or superclass) is the class whose properties
and methods are inherited by other classes. It contains common functionality that can be shared across
multiple derived classes.
• Derived (or Child) Class: The derived class (also known as the child or subclass) is a class that inherits
properties and methods from the base class. It can use the features of the base class and can also extend or
modify the inherited properties and behaviors to suit its specific needs.

Basic Syntax of Inheritance: In C++, inheritance is specified using a colon (:) followed by the access specifier (such as
public) and the name of the base class:

class BaseClass {
// Properties and methods of the base class
};

class DerivedClass : public BaseClass {


// Additional properties and methods of the derived class
};

Program of inheritance with a base class and a derived class.

Example:
#include <iostream>
#include <string>

// Base class
class Animal {
public:
void eat() {
std::cout << "This animal is eating." << std::endl;
}
};

// Derived class
class Dog : public Animal {
public:
void bark() {
std::cout << "The dog is barking." << std::endl;
}
};

int main() {
Dog myDog;

// Calling base class method


myDog.eat(); // Inherited from Animal

// Calling derived class method


myDog.bark();

return 0;
}

Abstract Classes:
An abstract class is a class that is designed to be inherited by other classes but is not meant to be instantiated
directly. It usually includes pure virtual functions, which are declared by assigning 0 to a virtual function. These pure
virtual functions force derived classes to implement their own versions, making the abstract class serve as a
blueprint for the derived classes.

Benefits of Abstract Classes


1. Polymorphism: Abstract classes enable polymorphism, allowing functions to operate on objects of
different derived types through base class pointers.
2. Code Reusability: Abstract classes allow common functionality to be shared, reducing duplication.
3. Clear Design: They provide a clear interface that derived classes must follow, ensuring consistency
across different implementations.
Program of Abstract Class and Inheritance

Example:
#include <iostream>

class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};

class Circle : public Shape {


public:
void draw() override {
std::cout << "Drawing Circle" << std::endl;
}
};

int main() {
Circle circle;
circle.draw(); // Calls the derived class implementation
return 0;
}

In this example: Circle inherits from Shape and provides an implementation for the draw() function, Shape serves as
an abstract base class that defines a common interface for all shapes.

Types of Inheritance:
Single Inheritance: A derived class inherits from only one base class.
class A { /* Base class */ };
class B : public A { /* Derived class */ };

Multiple Inheritance: A derived class inherits from more than one base class.
class A { /* Base class */ };
class B { /* Another base class */ };
class C : public A, public B { /* Derived class */ };

Multilevel Inheritance: A class is derived from a class that is also derived from another class.
class A { /* Base class */ };
class B : public A { /* Intermediate derived class */ };
class C : public B { /* Final derived class */ };

Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
class A { /* Base class */ };
class B : public A { /* Derived class */ };
class C : public A { /* Another derived class */ };

Hybrid Inheritance: A combination of multiple and multilevel inheritance. It is a complex inheritance structure
that can lead to a diamond problem (resolved in C++ by virtual inheritance).
class Vehicle { // Base class };
class Engine : public Vehicle { // Derived from Vehicle };
class Wheels : public Vehicle { // Derived from Vehicle };
class Car : public Engine, public Wheels { // Derived from both Engine and Wheels, creating a hybrid structure };
Access Specifiers in Inheritance
The access specifier (public, protected, private) used in inheritance determines how the members of the base class
are inherited:
• Public Inheritance: Public members of the base class remain public in the derived class, and
protected members remain protected.
• Protected Inheritance: Public and protected members of the base class become protected in the
derived class.
• Private Inheritance: Public and protected members of the base class become private in the derived
class.
Benefits of Inheritance
• Code Reusability: Inheritance allows classes to reuse code from other classes, reducing duplication
and making code maintenance easier.
• Extensibility: New features can be added to derived classes without modifying the base class.

Derived classes

Derived classes allow new classes to inherit properties and behaviors from existing classes, forming relationships
that enable code reuse and extensibility. Derived classes are defined using inheritance with visibility modes and can
use constructors to initialize inherited properties.

Visibility Modes- visibility mode (or access specifier) determines how the members of the base class are accessed in
the derived class. In C++, the three visibility modes are:
1. Public: Members of the base class retain their original access levels in the derived class.
2. Protected: Public and protected members of the base class become protected in the derived class.
3. Private: All inherited members of the base class become private in the derived class.

Types of Derivation
1. Public Derivation
• The public members of the base class remain public in the derived class.
• The protected members of the base class remain protected in the derived class.
• The private members of the base class are inaccessible in the derived class.
Example:
class Base {
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};

class Derived : public Base {


// public Member is public in Derived
// protected Member is protected in Derived
// private Member is inaccessible in Derived
};

2. Private Derivation
• Both public and protected members of the base class become private in the derived class.
• The private members of the base class remain inaccessible in the derived class.
Example:
class Derived : private Base {
// publicMember becomes private in Derived
// protectedMember becomes private in Derived
// privateMember is inaccessible in Derived
};

3. Protected Derivation
• Both public and protected members of the base class become protected in the derived class.
• The private members of the base class remain inaccessible in the derived class.
Example:
class Derived : protected Base {
// publicMember becomes protected in Derived
// protectedMember remains protected in Derived
// privateMember is inaccessible in Derived
};

Constructors in Derived Classes: Constructors of the base class are not inherited by the derived class. when a
derived class is instantiated, the base class constructor is called first, followed by the derived class constructor. This
ensures that the base part of the derived object is properly initialized before any additional initialization in the
derived class.
Program of Calling the Base Class Constructor:

Example:
#include <iostream>

class Base {
public:
Base(int x) {
std::cout << "Base constructor called with x = " << x << std::endl;
}
};

class Derived : public Base {


public:
Derived(int x, int y) : Base(x) { // Calls Base constructor with x
std::cout << "Derived constructor called with y = " << y << std::endl;
}
};

int main() {
Derived obj(10, 20);
return 0;
}

Containership: (also known as composition) is a form of association where one class contains objects of another
class as its members, rather than inheriting from it. This is often used to represent a “has-a” relationship.
Composition is used when you want to use the functionality of other classes within a class but don't require an
inheritance relationship.

Program of Containership:

Example:
#include <iostream>

class Engine {
public:
Engine() { std::cout << "Engine created\n"; }
void start() { std::cout << "Engine started\n"; }
};

class Car {
private:
Engine engine; // Car "has-an" Engine

public:
Car() { std::cout << "Car created\n"; }
void start() {
engine.start(); // Using Engine’s functionality within Car
std::cout << "Car started\n";
}
};

int main() {
Car myCar;
myCar.start();
return 0;
}

Virtual Base Classes


In cases of multiple inheritance, virtual base classes are used to solve the diamond problem. This occurs when a
class is derived from two classes that both inherit from a common base class, leading to ambiguity about which path
to follow.
By using virtual inheritance for the common base class, C++ ensures that only one instance of the base class is
created in the derived class, regardless of the multiple inheritance paths. This resolves the ambiguity and prevents
duplicated instances of the base class.
Program of Virtual Base Class to Solve the Diamond Problem:

Example:
#include <iostream>

class Person {
public:
Person() {
std::cout << "Person Constructor" << std::endl;
}
};

class Faculty : virtual public Person { // Virtual inheritance


public:
Faculty() {
std::cout << "Faculty Constructor" << std::endl;
}
};

class Student : virtual public Person { // Virtual inheritance


public:
Student() {
std::cout << "Student Constructor" << std::endl;
}
};

class TeachingAssistant : public Faculty, public Student {


public:
TeachingAssistant() {
std::cout << "TeachingAssistant Constructor" << std::endl;
}
};

int main() {
TeachingAssistant ta;
return 0;
}

You might also like