0% found this document useful (0 votes)
38 views235 pages

C++ Complete Unit

The document outlines the syllabus for a C++ programming course, covering topics such as language design, data types, object-oriented programming, functions, and file handling. It explains various concepts including parameter passing methods, binding, scope, recursion, and programming paradigms. Additionally, it distinguishes between imperative and declarative programming approaches, providing examples of languages associated with each paradigm.

Uploaded by

Karthi
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)
38 views235 pages

C++ Complete Unit

The document outlines the syllabus for a C++ programming course, covering topics such as language design, data types, object-oriented programming, functions, and file handling. It explains various concepts including parameter passing methods, binding, scope, recursion, and programming paradigms. Additionally, it distinguishes between imperative and declarative programming approaches, providing examples of languages associated with each paradigm.

Uploaded by

Karthi
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

CRACK CS IT WITH DIVYA

TRB COMPUTER SCIENCE


2025

PROGRAMMING WITH C++


DIVYA RAJESH

04-09-2025 CRACK CS IT WITH DIVYA 1


SYLLABUS CRACK CS IT WITH DIVYA

PROGRAMMING WITH C++


• Language Design and Translation Issues: Programming Language Concepts, Paradigms
and Models, Programming Environments, Virtual Computers and Binding Times,
Programming Language Syntax, Stages in Translation, Formal Transition Models.
• Elementary Data Types: Properties of Types and Objects, Scalar and Composite Data
Types.
• Object Oriented Programming: Class, Object, Encapsulation, Inheritance, Abstract Class,
Polymorphism.
• Basics of C++: Tokens, Identifiers, Variables and Constants, Data types, Operators,
Control statements.
• Functions: User-defined Functions, Parameter Passing, Virtual Functions.
• Class and Objects: Constructors and Destructors, Overloading, Inheritance, Templates.
• Files and Event Handling: Streams and Files, Multi-file Programs, Exception and Event
Handling.

04-09-2025 CRACK CS IT WITH DIVYA 2


CRACK CS IT WITH DIVYA

04-09-2025 CRACK CS IT WITH DIVYA 3


CRACK CS IT WITH DIVYA

Language Design and


Translation Issues

04-09-2025 CRACK CS IT WITH DIVYA 4


CRACK CS IT WITH DIVYA
PROGRAMMING LANGUAGE CONCEPTS
• A program is a set of instructions that helps a computer perform tasks.
This set of instructions is also called a script.
Programs are executed by the processor, whereas scripts are interpreted.
The languages used to write a program or set of instructions are called
programming languages.

Programming languages are broadly categorized into three types:


• Machine-level language
• Assembly-level language
• High-level language

04-09-2025 CRACK CS IT WITH DIVYA 5


CRACK CS IT WITH DIVYA
Parameter Passing
Arguments or parameters are used to transfer values from a calling
function to the function being called.
For example, if function B() is invoked from function A(), then A is
known as the caller function, and B is referred to as the called function
or callee function.
The values passed by the calling function to the called function are
called actual arguments, while the parameters defined in the called
function are known as formal arguments.

04-09-2025 CRACK CS IT WITH DIVYA 6


CRACK CS IT WITH DIVYA
Parameter passing models
▪ Formal parameters follow one of three semantic models, based on how they
interact with actual parameters:
▪ They can receive data from the actual parameter,
▪ They can send data back to the actual parameter, or
▪ They can both receive and send data.
▪ These three models are referred to as:
▪ In mode – for receiving data only
▪ Out mode – for sending data only
▪ Inout mode – for both receiving and sending data

04-09-2025 CRACK CS IT WITH DIVYA 7


Models of Parameter passing CRACK CS IT WITH DIVYA
Caller Callee
( sub ( a, b, c) ( procedure sub ( x, y, z))

call x
a

In mode

return
y
b

Out mode
call
z
c return

Inout mode
Different parameter passing methods
CRACK CS IT WITH DIVYA

• Call by Value: A copy of the actual parameter is passed into the procedure. Changes
made inside the function do not affect the original variable.
• Call by Reference: A reference (or pointer) to the actual parameter is passed, allowing
the function to directly modify the original variable.
• Call by Result: A copy is returned from the procedure to the actual parameter after
execution, meaning changes inside the procedure are copied back after completion.
• Call by Value-Result (also known as Call by Value Return or Copy-Restore): A copy is
passed in, and another copy is sent back out after the function completes. Combines
call by value and call by result behavior.
• Call by Name (also called Call by Text): In pass-by-name, the function gets the name
(or expression) of the variable, not its value. For simple values, it behaves similarly to
call by reference.

04-09-2025 CRACK CS IT WITH DIVYA 9


Eg: call by value-in mode CRACK CS IT WITH DIVYA
#include <stdio.h>
void funEg(int a, int b)
{
a += b;
printf("In func, a = %d b = %d\n", a, b);
}
int main(void)
{
int x = 10, y = 12;
funEg(x, y);
printf("In main, x = %d y = %d\n", x, y);
return 0;
}
04-09-2025 CRACK CS IT WITH DIVYA 10
Eg:call by reference(inout mode) CRACK CS IT WITH DIVYA
#include <stdio.h>
void swapNum(int* i, int* j) In Inout Mode, the parameter can
{ be read and updated, meaning
int temp = *i; changes made in the function
*i = *j; directly affect the original variable.
*j = temp;
}
int main(void)
{
int a = 15, b = 100;
swapNum(&a, &b);
printf("a is %d and b is %d\n", a, b);
return 0;
}
04-09-2025 CRACK CS IT WITH DIVYA 11
Eg: Call by result (Out Mode) CRACK CS IT WITH DIVYA

fun(out int x) {
x = 30; The corresponding formal parameter acts
} as a local variable;
No value is transmitted to the subprogram;
main() { The formal parameter's value is copied to
y = 15; the actual parameter when the function
ends.
fun(y);
print(y);
}

04-09-2025 CRACK CS IT WITH DIVYA 12


Pass-by-Name (Inout Mode) CRACK CS IT WITH DIVYA
int a = 200; // Global variable
void P(int x) // every x will be replaced by a.
{
a = 1000; // this will update global variable a 200 to 1000.
print(x); // will print value of global a which is 1000.
a = a + 20; // 1000 + 20 and will be stored in global a as 1020.
x = x + 10; // will update the global variable a as 1020 + 10 = 1030.
print(x); // will print the global variable a which is 1030.
}void main()
{
P(a); // This will pass value of global a which is 200.
print(a); } // will print the global variable a which is 1030.
//after completion of program a will have the final value as 1030.

04-09-2025 CRACK CS IT WITH DIVYA 13


Binding in Programming CRACK CS IT WITH DIVYA

Binding is the association between two things in a program, such as:


▪ A variable and its type or value
▪ An operation and the symbol that represents it
Examples:
Binding a class name to a class
Binding a variable name to a value

04-09-2025 CRACK CS IT WITH DIVYA 14


Static Binding and Static Type Binding
CRACK CS IT WITH DIVYA

Static Binding (also called Compile-Time Binding):


The association between a function call and its definition is determined at compile time.
This is used in features like:
•Function Overloading
•Operator Overloading
It is faster because the decision is made before the program runs.

Static Type Binding:


The type of a variable is determined and fixed at compile time.
Once declared (e.g., int x;), the variable cannot change its type later.
Found in statically typed languages like C, C++, Java.

04-09-2025 CRACK CS IT WITH DIVYA 15


Dynamic Binding and Dynamic Type Binding
CRACK CS IT WITH DIVYA

Dynamic Binding (also called Late Binding):


The connection between a function call and its actual definition is made at runtime.
This allows more flexible behavior, especially in object-oriented programming.
Eg:
Virtual functions in C++Method
overriding in Java
Dynamic Type Binding:

The type of a variable is determined at runtime, and it can change during execution.
This is common in interpreted languages like Python and JavaScript.
x=5 # x is an int
x = "text" # now x is a string

04-09-2025 CRACK CS IT WITH DIVYA 16


Scope in Programming CRACK CS IT WITH DIVYA

• Scope refers to the textual region of a program where a binding (e.g., variable or
function name) is valid and accessible.
• If you use a name outside its scope, it either:
• Causes an error (undefined), or
• Refers to a different binding.
• Types of Scoping:
• Static scoping
• Dynamic scoping

04-09-2025 CRACK CS IT WITH DIVYA 17


Static Scoping (Also Called LexicalCRACK
Scoping)
CS IT WITH DIVYA

• In static scoping, a variable refers to the closest enclosing scope (block or


function) at the time of writing the code, not at runtime.
• The compiler first looks for the variable in the current block, then moves outward
to enclosing blocks, and finally to global scope.
• The variable's meaning is determined based on the program's structure, not the
call order.
• Used in most modern languages, including:
• C, C++, Java, Pascal, Algol, Python

04-09-2025 CRACK CS IT WITH DIVYA 18


CRACK CS IT WITH DIVYA
Eg for Static scoping
int a = 10, b = 20;
int main() {
int a = 5;
{
int c;
c = b/a;
printf(“%d”, c);
}
}

04-09-2025 CRACK CS IT WITH DIVYA 19


Dynamic Scoping CRACK CS IT WITH DIVYA

• In dynamic scoping, a variable's value is resolved by looking at the call stack at


runtime.
• The program first checks the current function's block, then searches the calling
function, and continues up the chain of callers until the variable is found.
• Unlike static scoping, it depends on the order of function calls, not the code
structure.
• Used in:
• Bash, LaTeX, and the original Lisp

04-09-2025 CRACK CS IT WITH DIVYA 20


int fun1(int);
CRACK CS IT WITH DIVYA
int fun2(int);
int a = 5;
int main() {
int a = 10;
a = fun1(a);
printf(“%d”,a);}
int fun1(int b) {
Eg: Dynamic Scoping
b = b + 10;
b = fun2(b);
return b;}
int fun2(int b){
int c;
c = a + b; return c;}
04-09-2025 CRACK CS IT WITH DIVYA 21
Recursion CRACK CS IT WITH DIVYA

• Recursion is a technique where a function solves a problem by calling itself with


a smaller or simpler version of the original problem.
• A recursive function keeps calling itself until it reaches a base case — a condition
that stops the recursion.
• Without a base case, the function would call itself endlessly, leading to a stack
overflow error (crash).
• Eg:
• A function calculating a factorial (like 5! = 5 × 4 × 3 × 2 × 1) can use recursion by
calling itself with smaller values (n-1) until it reaches 1.

04-09-2025 CRACK CS IT WITH DIVYA 22


CRACK CS IT WITH DIVYA
Eg: Recursion
int factorial(int n) { factorial(5)
if (n == 1) // Base case = 5 * factorial(4)
return 1; = 5 * 4 * factorial(3)
else = 5 * 4 * 3 * factorial(2)
return n * factorial(n - 1); = 5 * 4 * 3 * 2 * factorial(1)
// Recursive call =5*4*3*2*1
} = 120

04-09-2025 CRACK CS IT WITH DIVYA 23


Paradigms and Models CRACK CS IT WITH DIVYA

• Paradigm can also be termed as a method to solve some problem or perform a


task.
• A programming paradigm is an approach to solving problems using a
programming language. It can also be described as a method to solve a problem
using tools and techniques available to us by following a specific approach.
• There are many programming languages, but all of them need to follow some
strategy when implemented. This methodology or strategy is called a paradigm.
• Apart from the variety of programming languages, there are many paradigms to
fulfill different needs and demands.

04-09-2025 CRACK CS IT WITH DIVYA 24


Programming Paradigms CRACK CS IT WITH DIVYA

Imperative Programming Paradigm


▪ Procedural Programming Paradigm
▪ Object-Oriented Programming
▪ Parallel Processing Approach

Declarative Programming Paradigm


▪ Logic Programming Paradigm
▪ Functional Programming
▪ Database Processing Approach

04-09-2025 CRACK CS IT WITH DIVYA 25


Imperative Programming ParadigmCRACK CS IT WITH DIVYA
▪ One of the oldest programming paradigms.
▪ Has a close relationship with machine architecture.
▪ Involves giving the computer a sequence of instructions to follow step by step.
▪ Programs are written as a series of commands that change a program’s state
using variables, loops, and control statements.
▪ Simple and easy to understand
▪ Supports common constructs like loops, variables, conditionals, etc.
▪ Not ideal for solving complex problems
▪ Can become less efficient and harder to manage in large programs
▪ Examples of Imperative Languages:
▪ C, C++, Java, Python, JavaScript, PHP, BASIC, Fortran

04-09-2025 CRACK CS IT WITH DIVYA 26


Declarative Programming Paradigm
CRACK CS IT WITH DIVYA

• Focuses on what the program should accomplish, rather than how to do it.
• The programmer specifies the desired result, and the language figures out how
to achieve it.
• Uses specialized functions, rules, and pre-defined tools instead of step-by-step
instructions.
• Examples of Declarative Languages:
• Functional Languages: LISP, Haskell, Scala
• Logic Languages: Prolog, Absys, Alice
• Database Query Languages: SQL

04-09-2025 CRACK CS IT WITH DIVYA 27


CRACK CS IT WITH DIVYA

Imperative Programming Declarative Programming


Changes data step by step Focuses on what to do, not
using variables. how to do it.
Examples: Procedural and Examples: Functional and Logic
Object-Oriented Programming Programming
Languages: C, C++, Java,
Languages: SQL, Haskell, Prolog
Python

04-09-2025 CRACK CS IT WITH DIVYA 28


Programming Paradigms of Declarative
CRACK CS IT WITH DIVYA

Programming Logic Programming


Functional Programming Based on facts and rules, not
Focuses on what you want to step-by-step instructions.
achieve, not how. The system figures out answers
Based on functions that return based on its knowledge.
values. Useful in AI and machine
No changing data (no side learning (e.g. NLP).
effects). Examples of languages:
Examples of languages: Prolog, Absys, Alice, ASP
Haskell, Scala, Clojure, Erlang, F# (Answer Set Programming)

04-09-2025 CRACK CS IT WITH DIVYA 29


Programming Environments CRACK CS IT WITH DIVYA

• Although environment setup is not a component of any programming language,


it is the initial step that must be taken before beginning to write a program.
• Environment setup refers to the foundational setup that allows us to perform
programming. This means having the necessary software installed on our
computer to write, compile, and execute computer programs.
For instance, if you want to browse the Internet, your system must have the
following setup:
• An active Internet connection
• A web browser like Internet Explorer, Chrome, Safari, etc.

04-09-2025 CRACK CS IT WITH DIVYA 30


Programming Environments cont..
CRACK CS IT WITH DIVYA

• Similarly, to begin programming with any language, you will require the following
setup:
• A text editor to write computer programs.
• A compiler to convert the programs into binary format.
• An interpreter to run the programs directly.
• If you don’t have much experience with computers, setting up this software
might be difficult. In such cases, it is recommended to seek assistance from
someone with technical knowledge to help set up the programming environment
on your system. However, it is still important for you to understand what these
components are.

04-09-2025 CRACK CS IT WITH DIVYA 31


Virtual Computers and Binding Times
CRACK CS IT WITH DIVYA

Virtual Computers
▪ Simply put, a virtual computer is "a software-based emulation of a physical
computing environment.
▪ "Virtual computers are also referred to as virtual machines.
▪ The purpose of a virtual computer is to provide one or more simultaneous
execution environments where operating systems or other programs can run.
▪ A hypervisor or virtual machine monitor is the software that creates and manages
virtual machines.

04-09-2025 CRACK CS IT WITH DIVYA 32


Virtual Computers and Binding Times
CRACK CS IT WITH DIVYA

▪ Binding Time
▪ A source file contains many names whose properties need to be identified.
▪ These properties can be determined during different stages of a program’s life cycle.
▪ Examples of such properties include:
▪ The set of values linked to a type
▪ The type of a variable
▪ The memory location of a compiled function
▪ The value stored in a variable, etc.
Binding refers to the process of linking these properties with names.
▪ Binding time is the point during the program’s life cycle when this linking (association)
occurs.

04-09-2025 CRACK CS IT WITH DIVYA 33


Programming Language Syntax CRACK CS IT WITH DIVYA

Hello World Program in C


int main() {
/* printf() function to write Hello, World! */
printf("Hello, World!");
}

04-09-2025 CRACK CS IT WITH DIVYA 34


Stages in Translation CRACK CS IT WITH DIVYA

▪ Structure of Compiler: A compiler takes a source program as input and produces


an equivalent sequence of machine instructions as output.
▪ The compilation process is divided into a series of subprocesses called phases.
▪ A phase is a logically cohesive operation that takes one representation of the
source program as input and produces a target program in another
representation as output.

04-09-2025 CRACK CS IT WITH DIVYA 35


Source Code
Phases of a Compiler CRACK CS IT WITH DIVYA

Lexical Analysis

Syntax Analysis

Symbol table Semantic Analysis Error Handling

Intermediate Code
Generation

Code Optimization

Code generation
CRACK CS IT WITH DIVYA 36

Machine Language
04-09-2025 Code
Formal Transition Models CRACK CS IT WITH DIVYA

Lexical Symbol Syntax


Source
Analysis Table Analysis
Code

Object Code Syntax


code generation Tree

04-09-2025 CRACK CS IT WITH DIVYA 37


Formal Transition Model- Compilation Process
CRACK CS IT WITH DIVYA
Source Code:
The original program written in a high-level programming language.
Lexical Analysis:
The first phase of compilation. It breaks the source code into tokens and adds entries to the
Symbol Table.
Symbol Table:
Stores information about variables, functions, objects, etc., used in the source code.
Syntax Analysis:
Checks the syntax of the tokens using grammar rules and generates a Syntax Tree.
Syntax Tree:
A tree structure representing the grammatical structure of the source code.
Code Generation:
Translates the syntax tree into machine-level code.
Object Code:
The final output of the compiler: executable machine code.
04-09-2025 CRACK CS IT WITH DIVYA 38
Elementary Data Types: Properties ofCRACK
Types and
CS IT WITH DIVYA
Objects
▪ An elementary data object consists of a single data value, and a group of such
objects with a defined set of operations for creating and manipulating them is
known as an elementary data type. Examples of elementary data types include
integer, real, character, Boolean, pointer, etc.
▪ The essential components of elementary data types include the following –
▪ Attributes – Attributes are the features or characteristics that differentiate one
data object from another. The primary attributes of a data object include its
name, the address it is associated with, and its data type. Consider the following
declaration in C:
▪ Eg: int a;

04-09-2025 CRACK CS IT WITH DIVYA 39


Elementary Data Types: Properties ofCRACK
Types and
CS IT WITH DIVYA
Objects cont..

The declaration int a; specifies that a is an integer-type data object. Its attributes
are stored in a descriptor, which is a group of memory cells created by the compiler
and used during compilation.

Values – These are all possible values a data object can hold, determined by its
type. At any time, an elementary data object holds a single value from this set. For
example, int a; allows a to store one integer value, which can change during the
program’s execution.

04-09-2025 CRACK CS IT WITH DIVYA 40


Elementary Data Types: Properties ofCRACK
Types and
CS IT WITH DIVYA
Objects cont..
▪ Operations – An operation is defined as a mathematical function used to
manipulate data objects. It consists of the following components:
▪ Domain – This refers to the complete set of valid input arguments on which the
operation is defined.
▪ Range – It denotes the set of all possible outputs that an operation can generate.
▪ Action – The action of an operation indicates the result produced for a specific
set of input arguments.
▪ Algorithm – This describes the procedure used to compute the result for a given
set of arguments. It plays a role in determining how an operation performs its
action.
▪ Signature – A signature specifies the number, sequence, and data types of the
input arguments in the domain, as well as the order and data type of the result
produced by the operation.

04-09-2025 CRACK CS IT WITH DIVYA 41


Scalar and Composite Datatype CRACK CS IT WITH DIVYA

Scalar Data Types:


• Scalar data types are the most basic data types, designed to store a single, atomic
value. They have no internal components that can be individually accessed or
manipulated.
• Examples: Integers (e.g., 5, -10), Floating-point numbers (e.g., 3.14, -0.5),
Characters (e.g., 'A', 'z'), Booleans (e.g., true, false), Dates and Times.
Composite Data Types:
• Composite data types are constructed from other data types, allowing them to
store and organize multiple values within a single structure. Their internal
components can often be accessed and manipulated individually.
• Examples:Array,Structure,union

04-09-2025 CRACK CS IT WITH DIVYA 42


CRACK CS IT WITH DIVYA
––––––––––– programming paradigm is in which the desired
result is declared as the answer to a question about a system of
facts and rules

(A) Declarative
(B) Imperative
(C) Logic
(D) Functional

04-09-2025 CRACK CS IT WITH DIVYA 43


CRACK CS IT WITH DIVYA
––––––––––– programming paradigm is in which the desired
result is declared as the answer to a question about a system of
facts and rules

(A) Declarative
(B) Imperative
(C) Logic
(D) Functional

04-09-2025 CRACK CS IT WITH DIVYA 44


CRACK
What will be printed by the print statements in the program Pro CS IT WITH DIVYA
assuming
call by reference parameter passing is used?
Program Pro() {
A:3,2,5
a=5; b=2; c=10; B:2,3,5
fun(b,a,c); C:5,2,10
D:2,3,10
print a ;
print b ;
print c ; }
fun (a, b, c) {
b = b – 2;
c = a + b;}
04-09-2025 CRACK CS IT WITH DIVYA 45
What will be printed by the print statements in the program Pro assuming
CRACK CS IT WITH DIVYA
call by reference parameter passing is used?
Program Pro() {
a=5; b=2; c=10; A:3,2,5
fun(b,a,c); B:2,3,5
C:5,2,10
print a ; D:2,3,10
print b ;
print c ; }
fun (a, b, c) {
b = b – 2;
c = a + b;}

04-09-2025 CRACK CS IT WITH DIVYA 46


CRACK CS IT WITH DIVYA

Object oriented Programming

04-09-2025 CRACK CS IT WITH DIVYA 47


CRACK CS IT WITH DIVYA
What is Object Oriented Programming?
Object-Oriented Programming (OOP) is a way of designing programs around
objects, which combine data and functions. Its main principles are encapsulation
(hiding details), inheritance (reusing code), and polymorphism (different behaviors
through one interface). The goal of OOP is to keep data safe and allow changes only
in controlled ways.

04-09-2025 CRACK CS IT WITH DIVYA 48


Characteristics of an Object-OrientedCRACK
Programming
CS IT WITH DIVYA
Language
Polymorphis
m

Abstraction Inheritance

Oops
Concepts

class Encapsulation

object

04-09-2025 CRACK CS IT WITH DIVYA 49


Class in C++ CRACK CS IT WITH DIVYA

• A Class is the fundamental building block of Object-Oriented


Programming (OOP).
• It is a user-defined data type that encapsulates:
• Data Members → represent the properties (attributes) of the objects.
• Member Functions → represent the behavior (methods) of the objects.
• To access and use the data members and functions, we create an
instance (object) of the class.
• A Class acts as a blueprint for creating objects, defining how they will
store data and perform operations.

04-09-2025 CRACK CS IT WITH DIVYA 50


Object in C++ CRACK CS IT WITH DIVYA

• An object is a real-world entity in programming that contains data


and the methods to operate on that data.
• An Object is an instance of a Class.
• When a Class is defined, no memory is allocated.
• When an Object is created, memory is allocated for its data
members.
• Objects occupy space in memory and have an associated address,
similar to a structure or union.

04-09-2025 CRACK CS IT WITH DIVYA 51


CRACK CS IT WITH DIVYA
#include <iostream>
using namespace std;
class Car {
int model; // Data member
char brand[20]; // Data member
public:
void show() {
cout << "Car object created" << endl;
} };
int main() {
Car c1; // c1 is an object
c1.show();
return 0;
}
04-09-2025 CRACK CS IT WITH DIVYA 52
Access Modifiers in C++ CRACK CS IT WITH DIVYA
Access modifiers are used to implement an important feature of Object-Oriented
Programming known as Data Hiding.

• There are 3 types of access modifiers available in C++:


1. Public
2. Private
3. Protected

Note: If we do not specify any access modifiers for the

members inside the class then by default the access modifier for

the members will be Private.


04-09-2025 CRACK CS IT WITH DIVYA 53
CRACK CS IT WITH DIVYA
Access Specifier: Public
1. Public
▪ Members declared as public are accessible from anywhere in the
program.
▪ Both data members and functions declared public can be
accessed using the object of that class (with . operator).
▪ Even other classes can access them.

04-09-2025 CRACK CS IT WITH DIVYA 54


CRACK CS IT WITH DIVYA
Access Specifier: Private
2.Private
▪ Members declared as private are restricted.
▪ They can be accessed only inside the class.
▪ Objects or outside functions cannot access them directly.
▪ Only member functions of the same class and friend functions
can access private data.

04-09-2025 CRACK CS IT WITH DIVYA 55


class Car {
private: CRACK CS IT WITH DIVYA
int speed; // private data
public:
void setSpeed(int s) { // member function can access
private data speed = s;
}
void showSpeed() {
cout << "Speed: " << speed << endl; }
};
int main() {
Car c1;
// c1.speed = 100; //Error (private)
c1.setSpeed(100); // Access through member function
c1.showSpeed(); // Output: Speed: 100
}

04-09-2025 CRACK CS IT WITH DIVYA 56


CRACK CS IT WITH DIVYA
Access Specifier: Protected
3. Protected
▪ Works similar to private, meaning not accessible outside the class.
▪ But difference: members declared protected can be accessed in
derived classes (subclasses).

04-09-2025 CRACK CS IT WITH DIVYA 57


Encapsulation in C++ CRACK CS IT WITH DIVYA

Encapsulation means wrapping up data and functions into a single unit.


▪ In Object-Oriented Programming, it refers to binding together the data members
and the functions that operate on them.
▪ Encapsulation helps in data abstraction or data hiding, so that the internal details
are hidden from the outside world, and only necessary information is exposed.
Important Points
▪ Data (variables) and code (functions) are kept together inside a class.
▪ Access to data can be restricted using access specifiers (private, public,
protected).
▪ Ensures security and controlled access.

04-09-2025 CRACK CS IT WITH DIVYA 58


Eg program-Encapsulation CRACK CS IT WITH DIVYA
class Student { • Here, marks is hidden
private:
inside the class, just like
medicine inside a capsule.
int marks; // hidden data
• We cannot access it
public:
directly; we use
void setMarks(int m) { marks = m; } setMarks() and getMarks()
int getMarks() { return marks; } — this is Encapsulation."
};
int main() {
Student s1;
s1.setMarks(95);
cout << s1.getMarks();
}
04-09-2025 CRACK CS IT WITH DIVYA 59
Abstraction in C++ CRACK CS IT WITH DIVYA

Abstraction means displaying only essential information and hiding


the details.
▪ It helps the user focus on what an object does, not how it works.
▪ Achieved in C++ using classes and functions.
▪ The user interacts with functions (interface) without worrying
about internal logic.

04-09-2025 CRACK CS IT WITH DIVYA 60


Eg: Abstraction and encapsulation CRACK CS IT WITH DIVYA
class Car {
private:
int speed; // encapsulated data

public:
void setSpeed(int s) { speed = s; } // abstraction: hides internal details
void showSpeed() { cout << speed; } // abstraction
};
int main() {
Car myCar;
myCar.setSpeed(120); // user sets speed without knowing internal logic
myCar.showSpeed(); // user sees speed
}

04-09-2025 CRACK CS IT WITH DIVYA 61


Polymorphism in C++ CRACK CS IT WITH DIVYA

• Polymorphism → “Having many forms.”


• It is the ability of a function or operator to behave differently in
different situations.
• Behavior depends on the type of data or the context of use.
• C++ supports two main types:
• Function Overloading
• Operator Overloading
• Widely used in Inheritance to achieve flexibility.

04-09-2025 CRACK CS IT WITH DIVYA 62


Polymorphism CRACK CS IT WITH DIVYA

Compile Time Run Time

Function Operator
Virtual
Overloading Overloading
Functions

04-09-2025 CRACK CS IT WITH DIVYA 63


Function Overloading CRACK CS IT WITH DIVYA

Function overloading is using a single function name to perform


different types of tasks.
➢Multiple functions with the same name but different parameter lists.
➢Achieved by changing number of arguments or types of arguments.
➢Supported in C++ and Java.
➢Not allowed if functions differ only by return type.

04-09-2025 CRACK CS IT WITH DIVYA 64


Function Overloading Rules CRACK CS IT WITH DIVYA

For functions with the same name to be overloaded, their parameters must differ
by at least one of the following:
1.Different type of parameters
Eg: add(int a, int b)
add(double a, double b)
2.Different number of parameters
Eg: add(int a, int b)
add(int a, int b,int c)
3. Different sequence of parameters
Eg: add(int a, double b)
add(double a, int b)

04-09-2025 CRACK CS IT WITH DIVYA 65


CRACK CS IT WITH DIVYA
1. Function Overloading
Same function name → performs different tasks based on parameters.

#include <iostream>
using namespace std;

class Print {
public:
void show(int x) { cout << "Integer: " << x << endl; }
void show(double y) { cout << "Double: " << y << endl;
}
};

int main() {
Print p;
p.show(5); // calls first function
p.show(3.14); // calls second function
}
04-09-2025 CRACK CS IT WITH DIVYA 66
Operator Overloading CRACK CS IT WITH DIVYA

The process of making an operator exhibit different behaviors in different


instances is known as operator overloading.
Operator overloading allows us to redefine how operators like +, -, * work with
objects. Just like numbers can be added using +, we can define how two objects
should be added.
▪ Part of compile-time polymorphism
▪ It giving special meaning to an existing operator when applied to user-
defined types (like classes).
▪ It does not change the original meaning for built-in types; instead, it provides
additional meaning for class objects.

04-09-2025 CRACK CS IT WITH DIVYA 67


CRACK CS IT WITH DIVYA
Syntax of Operator Overloading
return_type operator op(argument_list)
{
// body of the function.
}

04-09-2025 CRACK CS IT WITH DIVYA 68


Rules for Operator Overloading CRACK CS IT WITH DIVYA

1. Only existing operators can be overloaded – we cannot create a new operator.


2. At least one operand must be a user-defined type (like an object).
Friend Function Restrictions
▪ Some operators cannot be overloaded using a friend function:
=, (), [], ->
▪ These operators must be overloaded using a member function.
Unary Operators
▪ If overloaded using a member function → no explicit argument is passed
(object itself is the operand).
▪ If overloaded using a friend function → it needs one argument (because the
object must be passed explicitly).

04-09-2025 CRACK CS IT WITH DIVYA 69


CRACK CS IT WITH DIVYA
Rules for Operator Overloading cont..
Binary Operators
• If overloaded using a member function → one explicit argument is
passed (the first operand is the invoking object, the second is passed).
• If overloaded using a friend function → two arguments are passed
(both operands must be passed explicitly).

04-09-2025 CRACK CS IT WITH DIVYA 70


#include <iostream> CRACK CS IT WITH DIVYA
using namespace std;
class Box {
public:
int size;
Box operator + (Box b) { Normally, + works only for built-in types
Box temp; (like int, float).But since we defined Box
temp.size = size + b.size; operator+(Box b), C++ now knows how to
return temp;
}
apply + on Box objects.
};
int main() {
Box b1, b2, b3;
b1.size = 5;
b2.size = 7;
b3 = b1 + b2; // calls overloaded +
cout << "Result = " << b3.size;
}

04-09-2025 CRACK CS IT WITH DIVYA 71


CRACK CS IT WITH DIVYA
Operator that cannot be overloaded are as follows:

1. Scope operator (::)


2. sizeof
3. member selector(.)
4. member pointer selector(*)
5. ternary operator(?:)

04-09-2025 CRACK CS IT WITH DIVYA 72


Operators that can be overloaded only
CRACK as
CS IT member
WITH DIVYA
functions, not as friend function:

1. Assignment operator =
2. Function call operator ()
3. Subscript operator []
4. Arrow operator ->

04-09-2025 CRACK CS IT WITH DIVYA 73


RECALL THIS PART AND CONTINUE CRACK CS IT WITH DIVYA

04-09-2025 CRACK CS IT WITH DIVYA 74


CRACK CS IT WITH DIVYA
RUN TIME POLYMORPHISM
When an object is linked with a function at run-time, it is called run-
time polymorphism.
The runtime polymorphism can be achieved by method overriding.

04-09-2025 CRACK CS IT WITH DIVYA 75


INHERITANCE CRACK CS IT WITH DIVYA

The capability of a class to derive properties and characteristics from


another class is called Inheritance.
Inheritance is one of the most important features of Object-Oriented
Programming.
Sub Class:
• The class that inherits properties from another class is called Sub class
or Derived Class.
• Super Class:
• The class whose properties are inherited by sub class is called Base
Class or Super class.

04-09-2025 CRACK CS IT WITH DIVYA 76


Reusability in Inheritance CRACK CS IT WITH DIVYA

Inheritance allows us to reuse existing code.


▪ If we want to create a new class, and an existing class already has
some fields or methods we need, we don’t have to rewrite them.
▪ Instead, we can derive (inherit) the new class from the existing
one.
▪ This way, the new class automatically gets the fields and methods
of the existing class.

04-09-2025 CRACK CS IT WITH DIVYA 77


CRACK CS IT WITH DIVYA
VEHICLE CLASS

CAR CLASS BIKE CLASS TRUCK CLASS

04-09-2025 CRACK CS IT WITH DIVYA 78


Modes of Inheritance in C++ CRACK CS IT WITH DIVYA

When one class is derived from another, the way members are
inherited depends on the mode of inheritance:
1. Public Inheritance
▪ Public members of the base class → remain public in the derived class.
▪ Protected members of the base class → remain protected in the derived
class.
▪ (Private members of the base class are never directly accessible.)
• This is the most common type of inheritance.

04-09-2025 CRACK CS IT WITH DIVYA 79


Modes of Inheritance in C++ cont..
CRACK CS IT WITH DIVYA

2. Protected Inheritance
▪ Public members of the base class → become protected in the
derived class.
▪ Protected members of the base class → remain protected in the
derived class.
Here, even public members of the base class are not public anymore.

04-09-2025 CRACK CS IT WITH DIVYA 80


Modes of Inheritance in C++ cont..CRACK CS IT WITH DIVYA
3. Private Inheritance
▪ Public members of the base class → become private in the derived
class.
▪ Protected members of the base class → also become private in
the derived class.
▪ Both are hidden from outside, only accessible within the derived
class itself.
Private members of the base class are never directly
accessible in any derived class.
Protected members of the base class can be directly
accessed inside the derived class.

04-09-2025 CRACK CS IT WITH DIVYA 81


CRACK CS IT WITH DIVYA

Base Class Member Types of Inheritance


Access specifier

Public Protected Private

Public Public Protected Private

protected Protected Protected Private

Private Hidden Hidden Hidden

04-09-2025 CRACK CS IT WITH DIVYA 82


Multiple Hybrid
CRACK CS IT WITH DIVYA

Inheritance Inheritance

Multilevel
Inheritance Inheritance

Single
Inheritance Hierarchical
Inheritance
04-09-2025 CRACK CS IT WITH DIVYA 83
TYPES OF INHERITANCE CRACK CS IT WITH DIVYA

1. Single Inheritance
• In single inheritance, a sub-class is derived from only one super class.
It inherits the properties and behavior of a single-parent class.
Sometimes, it is also known as simple inheritance.
CLASS ANIMAL

CLASS CAT

04-09-2025 CRACK CS IT WITH DIVYA 84


class Animal { // Base class
CRACK CS IT WITH DIVYA
public:
void sound() { OUTPUT
cout << "Animals make sound" << endl;
}
}; Animals make sound
Cat says Meow!
class Cat : public Animal { // Derived class
public:
void meow() {
cout << "Cat says Meow!" << endl;
}
};

int main() {
Cat c;
c.sound(); // Inherited from Animal
c.meow(); // Defined in Cat
}

04-09-2025 CRACK CS IT WITH DIVYA 85


TYPES OF INHERITANCE CRACK CS IT WITH DIVYA

2. Multiple Inheritance
In multiple inheritance, one sub-class is derived from more than one
classes. It inherits the properties and behavior of both the classes.

CLASS ANIMAL CLASS PET

CLASS CAT

04-09-2025 CRACK CS IT WITH DIVYA 86


class Animal { 2. Multiple Inheritance EXAMPLE

public: CRACK CS IT WITH DIVYA


int main() {
void eat() {
Cat c;
cout << "This animal can eat." << endl;
c.eat(); // from Animal
} };
c.play(); // from Pet
class Pet {
c.meow(); // from Cat
public:
return 0;
void play() {
}
cout << "This pet loves to play." << endl;
} };
// Cat inherits from both Animal and Pet
class Cat : public Animal, public Pet {
public:
void meow() {
cout << "The cat meows." << endl;
}
};
04-09-2025 CRACK CS IT WITH DIVYA 87
TYPES OF INHERITANCE CRACK CS IT WITH DIVYA

3. Multilevel Inheritance
In multilevel inheritance, a derived class is created from another
derived classes.
CLASS ANIMAL

CLASS MAMMAL

CLASS CAT

04-09-2025 CRACK CS IT WITH DIVYA 88


class Animal { 3. Multilevel Inheritance EXAMPLE
CRACK CS IT WITH DIVYA
public:
void eat() { cout << "This animal can eat.\n"; }
};

class Mammal : public Animal {


public:
void breathe() { cout << "This mammal breathes air.\n"; }
};

class Cat : public Mammal {


public:
void meow() { cout << "The cat meows.\n"; }
};
// Example use
Cat c;
c.eat();
c.breathe();
c.meow();

04-09-2025 CRACK CS IT WITH DIVYA 89


TYPES OF INHERITANCE CRACK CS IT WITH DIVYA

4. Hierarchical Inheritance
In Hierarchical inheritance, more than one sub-class is derived from a
single base classes.i.e, more than one derived class is created from a
single base class.
CLASS ANIMAL

CLASS CAT CLASS DOG

04-09-2025 CRACK CS IT WITH DIVYA 90


class Animal { CRACK CS IT WITH DIVYA
public:
void eat() { cout << "This animal can eat.\n"; }
};
class Cat : public Animal {
public:
void meow() { cout << "The cat meows.\n"; }
};
class Dog : public Animal {
public:
void bark() { cout << "The dog barks.\n"; }
};
// Example use
Cat c;
c.eat(); c.meow();
Dog d;
d.eat(); d.bark();
04-09-2025 CRACK CS IT WITH DIVYA 91
TYPES OF INHERITANCE CRACK CS IT WITH DIVYA

5. Hybrid Inheritance
Hybrid Inheritance = combination of two or more inheritance types
(like Hierarchical + Multiple).

CLASS ANIMAL

CLASS CAT CLASS DOG

CLASS PET
04-09-2025 CRACK CS IT WITH DIVYA 92
RECALL THIS PART AND CONTINUE CRACK CS IT WITH DIVYA

04-09-2025 CRACK CS IT WITH DIVYA 93


CRACK CS IT WITH DIVYA
RUN TIME POLYMORPHISM
When an object is linked with a function at run-time, it is called run-
time polymorphism.
The runtime polymorphism can be achieved by function overriding.

04-09-2025 CRACK CS IT WITH DIVYA 94


CRACK CS IT WITH DIVYA
FUNCTION OVERRIDING
▪ Function overriding means redefining a base class function in the
derived class with the same signature, that is, the same return type
and parameters.
▪ It can only be done inside the derived class.
▪ This feature allows the derived class to provide its own version of the
function that already exists in the base class.
▪ Since the function to be executed is decided at run time depending
on the object, method overriding comes under runtime
polymorphism.

04-09-2025 CRACK CS IT WITH DIVYA 95


class Animal {
public: CRACK CS IT WITH DIVYA
void sound() {
// Base class function
// Prints generic animal sound
} };
class Dog : public Animal {
public:
void sound() {
// Overridden function in derived class
// Prints dog-specific sound
} };
int main() {
Animal a;
Dog d;
a.sound(); // Calls Animal version
d.sound(); // Calls Dog version
}
04-09-2025 CRACK CS IT WITH DIVYA 96
Single Inheritance (no overriding) Single Inheritance (WITH overriding)
class Animal { class Animal { CRACK CS IT WITH DIVYA
public: public:
void eat() { void sound() { cout << "Generic animal
cout << "Animal eats food"; sound\n"; }
}}; };
class Cat : public Animal { class Dog : public Animal {
public: public:
void meow() { void sound() { cout << "Dog barks\n"; }
cout << "Cat meows"; };
}}; int main() {
int main() { Animal a;
Cat c; Dog d;
c.eat(); // uses parent function a.sound(); // Generic animal sound
c.meow(); // uses child function d.sound(); } // Dog barks
}
Child (Cat) uses parent’s method Child (Dog) redefines parent’s method sound (),
as it is. So parent version is replaced when called from the
04-09-2025 CRACK CS IT WITH DIVYA 97
child..
Single Inheritance (WITH overriding)
class Animal { CRACK CS IT WITH DIVYA
public:
void sound() { cout << "Generic animal
sound\n"; }
};
class Dog : public Animal {
public:
void sound() { cout << "Dog barks\n"; }
};
int main() { Child (Dog) redefines parent’s method sound (),
Animal a; So parent version is replaced when called from the
Dog d; child..
a.sound(); // Generic animal sound
d.sound(); } // Dog barks

04-09-2025 CRACK CS IT WITH DIVYA 98


Function Overloading Function Overriding
CRACK CS IT WITH DIVYA
It falls under Compile- It falls under Runtime
Time polymorphism Polymorphism
Redefinition of base class function
Multiple definitions of a function
in derived class with same
with different signatures
signature
Signatures must be different Signatures must be the same
Can be executed without Cannot be executed without
inheritance inheritance
They are in the same scope They are of different scopes.
Used when same function works Used when derived class gives
differently for different new definition for base class
parameters function

04-09-2025 CRACK CS IT WITH DIVYA 99


CRACK CS IT WITH DIVYA
Q. The feature that is not an Object
Oriented Programming concept :

(A) Dynamic binding

(B) Message passing

(C) Platform independent

(D) Data hiding

04-09-2025 CRACK CS IT WITH DIVYA 100


CRACK CS IT WITH DIVYA
Q. The feature that is not an Object
Oriented Programming concept :

(A) Dynamic binding

(B) Message passing

(C) Platform independent

(D) Data hiding

04-09-2025 CRACK CS IT WITH DIVYA 101


Q. class C {
public: CRACK CS IT WITH DIVYA
void f(int a) (cout << a:)
void f(int a, int b) (cout << a + b;);
void f(int a, int b, int c) (cout << a + b + c;)};
int main(){
C obj;
obj.f(10);
obj.f(10, 20);
obj.f(10, 20, 30);
return 0;}
The above C++ source code exemplifies which of the following principle with
respect to object-oriented programming?
(A) Abstraction
(B) Encapsulation
(C) Inheritance
(D) Polymorphism
04-09-2025 MH
CRACKSET 2024
CS IT WITH DIVYA 102
Q. class C {
CRACK CS IT WITH DIVYA
public:
void f(int a) (cout << a:)
void f(int a, int b) (cout << a + b;);
void f(int a, int b, int c) (cout << a + b + c;)};
int main(){
C obj;
obj.f(10);
obj.f(10, 20);
obj.f(10, 20, 30);
return 0;}
The above C++ source code exemplifies which of the following principle with respect to
object-oriented programming?
(A) Abstraction
(B) Encapsulation
(C) Inheritance
(D) Polymorphism

04-09-2025 CRACK CS IT WITH DIVYA 103


CRACK CS IT WITH DIVYA
Q. If data members are private, what can we do to access
them from the class object?

a) Private data members can never be accessed from


outside the class
b) Create public member functions to access those data
members
c) Create private member functions to access those data
members
d) Create protected member functions to access those
data members

04-09-2025 CRACK CS IT WITH DIVYA 104


CRACK CS IT WITH DIVYA
Q. If data members are private, what can we do to access
them from the class object?

a) Private data members can never be accessed from


outside the class
b) Create public member functions to access those data
members
c) Create private member functions to access those data
members
d) Create protected member functions to access those
data members

04-09-2025 CRACK CS IT WITH DIVYA 105


Friend Function and Friend Class in C++
CRACK CS IT WITH DIVYA

In C++, friend functions and friend classes allow certain functions or classes
to access private and protected members of another class.
This is useful when you want to give special access to some functions or
classes without making the data public.
1. Friend Class
A friend class can access private and protected members of another class.
Friendship is not mutual → if Class A is a friend of Class B, Class B is not
automatically a friend of A.
Declared using the friend keyword inside the class.
Can be declared in public, private, or protected sections — it works the
same.

04-09-2025 CRACK CS IT WITH DIVYA 106


CRACK CS IT WITH DIVYA
How to declare friend class?
class ABC {
// XYZ is a friend class of ABC
friend class XYZ;
}; // Base Class

class XYZ {
Statements;
}; // Friend Class

04-09-2025 CRACK CS IT WITH DIVYA 107


Eg for Friend Class CRACK CS IT WITH DIVYA

class Geeks {
private:
int a = 10;
friend class GFG; // GFG is friend class
};

class GFG {
public:
void show() {
Geeks g;
cout << g.a; // all member functions of GFG can access private data
}
};

04-09-2025 CRACK CS IT WITH DIVYA 108


Friend Function in C++ CRACK CS IT WITH DIVYA

A function outside a class that can access private/protected members


of that class because it is declared as a friend.
• It is not a member of the class.
• Only that function is allowed special access.
• Can be:
• A global function, or
• A member function of another class.

04-09-2025 CRACK CS IT WITH DIVYA 109


Friend Functions and Friend Classes CRACK
– Important
CS IT WITH DIVYA
Points
▪ Friends should be used only for limited purposes. Too many
functions or external classes declared as friends of a class with
private or protected data lessens encapsulation in OOP.
▪ Friendship is not mutual: If class A is a friend of B, then B doesn’t
become a friend of A automatically.
▪ Friendship is not inherited.
▪ The concept of friends does not exist in Java.

04-09-2025 CRACK CS IT WITH DIVYA 110


Let A be the base class in C++ and B be the derivedCRACK
class CS IT WITH
from A DIVYA
with protected inheritance.
Which of the following statement is false for class B?

1.Member function of class B can access protected data of class A


2.Member function of Class B can access public data of class A
3.Member function of class B cannot access private data of class A
4.Object of derived class B can access public base class data

UGC NET Dec 2019

04-09-2025 CRACK CS IT WITH DIVYA 111


Let A be the base class in C++ and B be the derivedCRACK
class CS IT WITH
from A DIVYA
with protected inheritance.
Which of the following statement is false for class B?

1.Member function of class B can access protected data of class A


2.Member function of Class B can access public data of class A
3.Member function of class B cannot access private data of class A
4.Object of derived class B can access public base class data

UGC NET Dec 2019

Protected members cannot be accessed by objects outside the class,


so the statement is false.

04-09-2025 CRACK CS IT WITH DIVYA 112


CRACK CS IT WITH DIVYA
Public members of A → become
protected in B
Protected members of A → remain
protected in B
Private members of A → never
accessible in B

04-09-2025 CRACK CS IT WITH DIVYA 113


CRACK CS IT WITH DIVYA

Introduction to C++
Programming Language

04-09-2025 CRACK CS IT WITH DIVYA 114


CRACK CS IT WITH DIVYA
What is C++?
▪ C++ is a general-purpose programming language developed by Bjarne Stroustrup

In 1979.

▪ It was created as an enhancement of the C language, adding features of object-


oriented programming (OOP).
▪ C++ is a middle-level language:
• Combines features of high-level languages (like OOP, exception handling).
• Offers low-level features (like memory access and system-level
programming).

04-09-2025 CRACK CS IT WITH DIVYA 115


CRACK CS IT WITH DIVYA

BASICS OF C++

04-09-2025 CRACK CS IT WITH DIVYA 116


C++ Syntax CRACK CS IT WITH DIVYA
Header files #include <iostream>
// Standard Namespace
Namespace using namespace std;
// Main Function
Main Function int main()
Blocks {
// Declaration of Variable Comments
identifiers
int num1 = 24;
keywords int num2 = 34;
int result = num1 + num2; semicolons
// Output
Basic Output cout cout << result << endl;
// Return Statement
return 0;
04-09-2025 } CRACK CS IT WITH DIVYA 117
Tokens CRACK CS IT WITH DIVYA

• Tokens are the smallest building block of C++ programs that the
compiler understands.

Keywords

Punctuators Operators

C++ Tokens
Strings Identifiers

Constants

04-09-2025 CRACK CS IT WITH DIVYA 118


Identifiers CRACK CS IT WITH DIVYA

In C++, entities like variables, functions, classes, or structs must be


given unique names so that they can be identified. These unique
names are called identifiers.
Example:
string first_name = “Madhav";
Here, first_name is an identifier.

04-09-2025 CRACK CS IT WITH DIVYA 119


Rules for Identifiers CRACK CS IT WITH DIVYA

▪ An identifier can only begin with a letter or an underscore (_).


▪ It can include letters (A–Z, a–z), digits (0–9), and underscores (_) only.
▪ White spaces or special characters are not allowed.
▪ Keywords cannot be used as identifiers because they are reserved
words (e.g., string, int, class, struct).
▪ C++ is case-sensitive.so first_name and First_name are considered
different identifiers.

04-09-2025 CRACK CS IT WITH DIVYA 120


CRACK CS IT WITH DIVYA
keywords
▪ Keywords in C++ are the tokens that are the reserved words in
programming languages that have their specific meaning and
functionalities within a program.
▪ Keywords cannot be used as an identifier to name any variables.
• There are 95 keywords reserved in C++.
Eg: int,float,friend,case,const,do,extern

04-09-2025 CRACK CS IT WITH DIVYA 121


List of all keywords in C++
CRACK CS IT WITH DIVYA

04-09-2025 CRACK CS IT WITH DIVYA 122


Constants CRACK CS IT WITH DIVYA

Constants are tokens in C++ used to define variables at the time of initialization.
▪ Once a constant is assigned a value, it cannot be changed later in the program.
Ways to Define Constants
1. Using const or constexpr keyword
const int age = 18; // value cannot be modified
constexpr int days = 7; // evaluated at compile time
2. Using #define preprocessor directive
#define PI 3.14
▪ Constants created using the #define preprocessor are called "macro constants“.
▪ The value is substituted during preprocessing.

04-09-2025 CRACK CS IT WITH DIVYA 123


Constant cont… CRACK CS IT WITH DIVYA
Difference between constexpr and const
constexpr
• Value is initialized at compile time.
• Value must be known before compilation.
const
• Can be initialized at compile time or runtime.
• More flexible compared to constexpr.

const int a = 10; // valid (runtime or compile time)


int x = 5;
const int b = x; // valid (runtime initialization)

constexpr int c = 20; // valid (compile-time constant)


constexpr int d = x; // error, x is not known at compile time

04-09-2025 CRACK CS IT WITH DIVYA 124


Punctuators CRACK CS IT WITH DIVYA
Punctuators are the token characters having specific meanings within the
syntax of the programming language.
Below are the most common punctuators used in C++ programming:
➢Semicolon (;): It is used to terminate the statement.
➢Square brackets []: They are used to store array elements.
➢Curly Braces {}: They are used to define blocks of code.
➢Double-quote ("): It is used to enclose string literals.
➢Single-quote ('): It is used to enclose character literals.

04-09-2025 CRACK CS IT WITH DIVYA 125


Operators CRACK CS IT WITH DIVYA

Operators are special symbols in C++ used to perform operations on operands


(variables, constants, or expressions).
A + B // A and B are operands, '+' is an operator
Types of Operators in C++
1.Unary Operators
Work with a single operand.
Example: Increment and Decrement operators.
• ++ (Increment): increases the value of operand by 1.
• -- (Decrement): decreases the value of operand by 1.

04-09-2025 CRACK CS IT WITH DIVYA 126


Operators cont.. CRACK CS IT WITH DIVYA

2. Binary Operators
3. Ternary Operator
Work with two operands.
The only operator that works with three
Examples: operands.
a) Arithmetic Operators Also called the conditional operator.
+-*/% Expression1 ? Expression2 : Expression3;
b) Comparison Operators
== != < > <= >= If Expression1 is true, then Expression2 is
c) Logical Operators executed.
&& || ! Otherwise, Expression3 is executed
d) Assignment Operators
= += -= *= /= %=
e) Bitwise Operators (except bitwise not)
& | ^ << >>
04-09-2025 CRACK CS IT WITH DIVYA 127
CRACK CS IT WITH DIVYA
Variables
▪ Variables are user-defined names assigned to specific memory locations where
values are stored.
▪ They are also known as identifiers.
▪ Rules for naming identifiers must be followed when naming variables.
▪ Called symbolic variables because they represent named memory locations.
▪ Two Values Associated with a Variable: R value and L value.
▪ R-value: The data stored in a memory location (i.e., the actual value).
▪ L-value: The memory address where the R-value is stored (i.e., the variable name
pointing to a memory location).

04-09-2025 CRACK CS IT WITH DIVYA 128


What is Dynamic Initialization? CRACK CS IT WITH DIVYA
Dynamic Initialization means initializing a variable at runtime using values already
input or computed during program execution.
#include <iostream>
using namespace std;
int main()
{
int num1, num2;
cout << "\n Enter number 1: ";
cin >> num1;
cout << "\n Enter number 2: ";
cin >> num2;

int sum = num1 + num2; // Dynamic


initialization
cout << "\n Average: " << sum / 2;
}

04-09-2025 CRACK CS IT WITH DIVYA 129


Formatting Output CRACK CS IT WITH DIVYA
Helps in creating clear and readable output for users.
Manipulators in C++ are special functions used with insertion (<<) and extraction (>>)
operators to format output.
Common Output Manipulators in C++
endl – Insert a new line and flush the output buffer
setw – Set width of the output field
setfill – Fill the output field with a specific character
setprecision – Set the number of digits after the decimal point
setf – Set format flags (e.g., for fixed or scientific notation)

endl is part of the <iostream> header.


setw, setfill, setprecision, and setf are part of the <iomanip> header.

04-09-2025 CRACK CS IT WITH DIVYA 130


Classification of Datatypes CRACK CS IT WITH DIVYA

Data Type in
C++

Basic Data Derived Data User Defined


Types Types Data Types
int array class
float pointer structure
double reference union
char function Enumeration
bool
void
Datatypes CRACK CS IT WITH DIVYA

• Data types specify the type of data a variable can store.


• When a variable is defined, the compiler allocates memory for it
based on its data type.
• Different data types require different amounts of memory.

04-09-2025 CRACK CS IT WITH DIVYA 132


1. Character Data Type (char) CRACK CS IT WITH DIVYA

Used to store a single character. #include <iostream>


using namespace std;
Size: 1 byte
Stores characters in single quotes (' '). int main() {
Can store up to 256 ASCII characters. char c = 'A';
cout << c;
return 0;
}

04-09-2025 CRACK CS IT WITH DIVYA 133


2. Integer Data Type (int) CRACK CS IT WITH DIVYA

Used to store integer numbers.


Size: 4 bytes (on 64-bit systems).
Supports binary, octal, decimal, and hexadecimal.
#include <iostream>
using namespace std;

int main() {
int x = 25;
cout << x << endl;

x = 0x15; // Hexadecimal
cout << x;
return 0;
04-09-2025 } CRACK CS IT WITH DIVYA 134
3. Boolean Data Type (bool) CRACK CS IT WITH DIVYA

Stores logical values → true (1) or false (0).


Size: 1 byte.
#include <iostream>
using namespace std;

int main() {
bool isTrue = true;
cout << isTrue;
return 0;
}

04-09-2025 CRACK CS IT WITH DIVYA 135


4. Floating Point Data Type (float)CRACK CS IT WITH DIVYA
Stores numbers with decimal points.
Size: 4 bytes (on 64-bit systems).

#include <iostream>
using namespace std;

int main() {
float f = 36.5;
cout << f;
return 0;
}

04-09-2025 CRACK CS IT WITH DIVYA 136


5. Double Data Type (double) CRACK CS IT WITH DIVYA

Stores decimal numbers with higher precision.


Size: 8 bytes (on 64-bit systems)

#include <iostream>
using namespace std;

int main() {
double pi = 3.1415926535;
cout << pi;
return 0;
}

04-09-2025 CRACK CS IT WITH DIVYA 137


6. Void Data Type (void) CRACK CS IT WITH DIVYA

▪ Represents absence of value.


▪ Cannot create variables of void type.
▪ Used for functions that don’t return any value and void pointers

04-09-2025 CRACK CS IT WITH DIVYA 138


Data Type Conversion CRACK CS IT WITH DIVYA

Type Conversion is the process of converting one fundamental data


type into another in C++.
Types of Type Conversion:
• Implicit Type Conversion
• Explicit Type Conversion

04-09-2025 CRACK CS IT WITH DIVYA 139


Data Type Conversion CRACK CS IT WITH DIVYA

(1) Implicit Type Conversion:: It is performed automatically by the compiler.


• Also called Automatic Conversion.
• Happens when different data types are intermixed in an expression.
• The smaller type is promoted to the wider type, called Type Promotion.

#include <iostream>
using namespace std;
int main() Output: 9.14
{
int a = 6;
float b = 3.14;
cout << a + b;
}
04-09-2025 CRACK CS IT WITH DIVYA 140
Data Type Conversion CRACK CS IT WITH DIVYA

(1) Explicit Type Conversion:


Explicit type conversion (also called type casting) allows the programmer to
convert a variable from one data type to another manually.
Syntax:(type-name) expression;

#include <iostream>
using namespace std;
int main() Output: 78
{
float x = 78.685;
cout << (int)x;
}

04-09-2025 CRACK CS IT WITH DIVYA 141


Data Type Conversion CRACK CS IT WITH DIVYA

❑Important Notes on Explicit Conversion:


Assigning a larger type to a smaller type (like float to int, long to short)
can cause:
• Loss of precision (double to float)
• Loss of fractional part( float to int)
• Undefined results if the value is out of range(long to short)

04-09-2025 CRACK CS IT WITH DIVYA 142


Size of Data Types in C++ CRACK CS IT WITH DIVYA

Data type size depends on system architecture (32-bit vs 64-bit) and compiler.
On same architecture, sizes remain the same.
Use sizeof operator to check sizes.
#include <iostream> Size of int: 4 bytes
using namespace std; Size of char: 1 byte
int main() { Size of float: 4 bytes
cout << "Size of int: " << sizeof(int) << " bytes" << endl; Size of double: 8 bytes
cout << "Size of char: " << sizeof(char) << " byte" << endl;
cout << "Size of float: " << sizeof(float) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes";
return 0;
}

04-09-2025 CRACK CS IT WITH DIVYA 143


Data Type Modifiers CRACK CS IT WITH DIVYA

Keywords used to change size or range of existing data types.


Modifiers: short, long, signed, unsigned.

int var1; // 4 bytes


long int var2; // 8 bytes

04-09-2025 CRACK CS IT WITH DIVYA 144


Control Statements in C++ CRACK CS IT WITH DIVYA
Decision-making is the process of controlling which part of code should be
executed based on a condition.
In C++, this is done using conditional statements (decision control statements).
Types of Decision-Making Statements in C++
1. if Statement
Executes a block of code if the condition is true.

int age = 19; Output:


if (age > 18) { allowed to vote
cout << "allowed to vote";
}

04-09-2025 CRACK CS IT WITH DIVYA 145


CRACK CS IT WITH DIVYA
Control Statements in C++ cont..
2. if-else Statement
Executes one block if the condition is true, otherwise another.

int n = 5;
if (n > 0) { Output:
cout << "number is positive."; number is positive.
} else {
cout << "number is non-positive.";
}

04-09-2025 CRACK CS IT WITH DIVYA 146


CRACK CS IT WITH DIVYA
Control Statements in C++ cont..
3. if-else-if Ladder
Checks multiple conditions sequentially.

int age = 18;


if (age < 13) { Output:
cout << "child"; Growing stage
} else if (age >= 1 && age <= 18) {
cout << "Growing stage";
} else {
cout << "adult";
}

04-09-2025 CRACK CS IT WITH DIVYA 147


Control Statements in C++ cont.. CRACK CS IT WITH DIVYA

4. Nested if-else
Allows checking conditions inside another if.
int n = 44;
if (n > 0) { Output:
if (n % 2 == 0) { positive and even number
cout << "positive and even number";
} else {
cout << "positive and odd number";
}
} else if (n == 0) {
cout << "the number is zero";
} else {
cout << "the number is negative";
}
04-09-2025 CRACK CS IT WITH DIVYA 148
5. Switch Statement CRACK CS IT WITH DIVYA

Used when many cases depend on a single variable.


char c = 'B';
switch (c) {
case 'A': cout << “UGC NET"; OUTPUT:
break; GATE CS
case 'B': cout << “GATE CS";
break;
default: cout << "invalid input";
}

04-09-2025 CRACK CS IT WITH DIVYA 149


6. Ternary Operator ( ?: ) CRACK CS IT WITH DIVYA

• Compact form of if-else.


int num1 = 10, num2 = 40; Output: 40
int max = (num1 > num2) ? num1 : num2;
cout << max;

04-09-2025 CRACK CS IT WITH DIVYA 150


7. Jump Statements CRACK CS IT WITH DIVYA

a) break
• Exits loop/switch immediately.

for (int i = 0; i < 5; i++) { Output:


0
if (i == 3) break; 1
cout << i << endl; 2

04-09-2025 CRACK CS IT WITH DIVYA 151


7. Jump Statements cont.. CRACK CS IT WITH DIVYA

b) continue
Skips current iteration, continues next.
for (int i = 0; i < 5; i++) { Output:
if (i == 3) continue; 0
cout << i << endl; 1
} 2
4

04-09-2025 CRACK CS IT WITH DIVYA 152


7. Jump Statements cont.. CRACK CS IT WITH DIVYA

c) goto
Transfers control to a labeled statement. (Not recommended in modern
C++.)
int age = 17;
if (age < 18) { Output:
goto Noteligible; You are not eligible to vote!
}
cout << "You can vote!";
Noteligible:
cout << "You are not eligible to vote!\n";

04-09-2025 CRACK CS IT WITH DIVYA 153


CRACK CS IT WITH DIVYA
7. Jump Statements cont..
d) return
Exits a function and optionally sends back a value.
int add(int a, int b) {
return a + b; Output: The sum
} is: 8

int main() {
int res = add(3, 5);
cout << "The sum is: " << res;
}

04-09-2025 CRACK CS IT WITH DIVYA 154


CRACK CS IT WITH DIVYA

Which of these types is not provided by


C but is provided by C++?

a. double

b. float

c. bool

d. int

04-09-2025 CRACK CS IT WITH DIVYA 155


CRACK CS IT WITH DIVYA
Which of these types is not provided by C but
is provided by C++?

a. double

b. float

c. bool

d. int

04-09-2025 CRACK CS IT WITH DIVYA 156


CRACK CS IT WITH DIVYA

Which of these won’t return any value?

a. void
b. null
c. free
d. empty

04-09-2025 CRACK CS IT WITH DIVYA 157


CRACK CS IT WITH DIVYA

Which of these won’t return any value?

a. void
b. null
c. free
d. empty

04-09-2025 CRACK CS IT WITH DIVYA 158


Loops in C++ CRACK CS IT WITH DIVYA

Loops are used when we want to repeat a block of code multiple times without
rewriting it again and again.
1. for loop
The for loop is an entry-controlled loop. It is used when the number of iterations is
known.
for (initialization; condition; updation) {
// code
}

for (int i = 1; i <= 5; i++) {


cout << i << " "; Output: 1 2 3 4 5
}

04-09-2025 CRACK CS IT WITH DIVYA 159


Loops in C++ cont.. CRACK CS IT WITH DIVYA

• The while loop is also entry-controlled. It is used when the number of


iterations is not known beforehand. The loop runs as long as the condition
is true.
Example:
Syntax: int i = 1;
while •
while (i <= 5) {
output:1 2 3 4 5
(condition) { cout << i << " ";
// body i++;
// update }
}

04-09-2025 CRACK CS IT WITH DIVYA 160


Loops in C++ cont.. CRACK CS IT WITH DIVYA

3. do-while loop
• Exit-controlled loop.
• Body executes at least once, even if condition is false.

Syntax int i = 1;
do { do {
// body cout << i << " "; Output: 1 2 3 4 5
// update i++;
} while (condition); } while (i <= 5);

04-09-2025 CRACK CS IT WITH DIVYA 161


What will be the output of the following C++ code?
CRACK CS IT WITH DIVYA

#include <iostream>
using namespace std; A: 543
int main () B : 5432
{ C : 54
int n; D : 432
for (n = 5; n > 0; n--)
{
cout << n;
if (n == 3)
break;
}
return 0;
}

04-09-2025 CRACK CS IT WITH DIVYA 162


What will be the output of the following C++ code?
CRACK CS IT WITH DIVYA

#include <iostream>
using namespace std; A: 543
int main () B : 5432
{ C : 54
int n; D : 432
for (n = 5; n > 0; n--)
{
cout << n;
if (n == 3)
break;
}
return 0;
}

04-09-2025 CRACK CS IT WITH DIVYA 163


CRACK CS IT WITH DIVYA
What will be the result of the following statement?
char ch = 'B';
cout << (int) ch;
Option 1: B
Option 2: b
Option 3: 65
Option 4: 66

04-09-2025 CRACK CS IT WITH DIVYA 164


CRACK CS IT WITH DIVYA
What will be the result of the following statement?
char ch = 'B';
cout << (int) ch;
Option 1: B
Option 2: b
Option 3: 65
Option 4: 66

04-09-2025 CRACK CS IT WITH DIVYA 165


CRACK CS IT WITH DIVYA
Important ASCII values

CHARACTER ASCII VALUE


A 65
Z 90
a 97
z 122
0 48
9 57

04-09-2025 CRACK CS IT WITH DIVYA 166


CRACK CS IT WITH DIVYA
The multi way branch statement:
(A) if
(B) if … else
(C) Switch
(D) for

04-09-2025 CRACK CS IT WITH DIVYA 167


CRACK CS IT WITH DIVYA
The multi way branch statement:
(A) if
(B) if … else
(C) Switch
(D) for

04-09-2025 CRACK CS IT WITH DIVYA 168


Types of Functions in C++ CRACK CS IT WITH DIVYA

C++ functions are categorized into:


1. Pre-defined / Built-in / Library Functions
Already written, tested, and stored in header files.
Can be directly used in programs.
2. User-defined Functions
Written by the programmer for specific tasks.
Syntax and logic are decided by the user.

04-09-2025 CRACK CS IT WITH DIVYA 169


C++ Header Files and Built-in Functions
CRACK CS IT WITH DIVYA

Header files store the code for built-in functions.


They have a .h extension.
Example: stdio.h, math.h, iostream, string.h, etc.
1. stdio.h – Standard I/O Header
Provides functions for input and output operations.
Functions in stdio.h:
getchar() – Reads a single character from the keyboard.
putchar() – Displays a single character to the screen.
gets() – Reads a line of input (until a newline is entered).
puts() – Displays a string followed by a newline.

04-09-2025 CRACK CS IT WITH DIVYA 170


C++ Header Files and Built-in Functions
CRACK CS IT WITH DIVYA

2. math.h – Mathematical Functions


Provides built-in math functions.
cos() – Returns cosine of an angle (in radians), value between -1 and 1.
sqrt() – Returns square root of a non-negative number; domain error if
negative input.
sin() – Returns sine of an angle (in radians), value between -1 and 1.
pow() – Returns base raised to the power of an exponent.

04-09-2025 CRACK CS IT WITH DIVYA 171


C++ Header Files and Built-in Functions
CRACK CS IT WITH DIVYA

3.string.h – String Handling Functions


strcmp() – Compares two strings lexicographically and returns:
• Positive if first differing char in string1 > string2
• Negative if first differing char in string1 < string2
• Zero if both strings are equal
strcat() – Appends the source string to the end of the target string.
strupr() – Converts a string to uppercase letters.
strlwr() – Converts a string to lowercase letters.
strlen(str) – Returns the length of the string str, excluding the null character \0.
Example: strlen("hello") returns 5.
strcpy(dest, src) – Copies the string src into dest.
After this, dest will contain the same string as src.

04-09-2025 CRACK CS IT WITH DIVYA 172


C++ Header Files and Built-in Functions
CRACK CS IT WITH DIVYA

Character functions (ctype.h)


isalnum(char c)
Checks if the character is alphanumeric (either a letter or a digit).
Returns non-zero if true, otherwise returns 0.
isalpha(char c)
Checks if the character is an alphabet letter (A-Z or a-z).
Returns non-zero if true.
isdigit(char c)
Returns non-zero if the character is a digit (0–9), else returns 0.
islower(char c)
Checks if the character is a lowercase letter (a–z).

04-09-2025 CRACK CS IT WITH DIVYA 173


CRACK CS IT WITH DIVYA
C++ Header Files and Built-in Functions
Character functions (ctype.h) cont..
isupper(char c)
Checks if the character is an uppercase letter (A–Z).
tolower(char c)
Converts an uppercase character to lowercase.
If not uppercase, returns the character unchanged.
toupper(char c)
Converts a lowercase character to uppercase.
If not lowercase, returns the character unchanged.

04-09-2025 CRACK CS IT WITH DIVYA 174


CRACK CS IT WITH DIVYA
C++ Header Files and Built-in Functions
iomanip – Input/Output Manipulators
Used for formatting output.
Functions/Manipulators in iomanip:

04-09-2025 CRACK CS IT WITH DIVYA 175


STORAGE CLASS CRACK CS IT WITH DIVYA

In C/C++, a storage class specifier tells the compiler how and where a variable
should be stored in memory, its scope (where it's accessible), and its lifetime (how
long it exists).
Types of Storage Classes:
1. auto Storage Class
Default for all local variables declared inside a block.
Declared variables automatically belong to auto.
Scope: Local
Default Value: Garbage
Memory Location: RAM
Lifetime: Till the end of its scope

04-09-2025 CRACK CS IT WITH DIVYA 176


STORAGE CLASS cont.. CRACK CS IT WITH DIVYA

2.extern Storage Class


Declares a variable that is defined elsewhere (possibly in another source file).
Used for external linkage in large programs with multiple files.
A global variable can be made extern by prefixing it with extern.
Properties:
Scope: Global
Default Value: Zero
Memory Location: RAM
Lifetime: Till the end of the program

04-09-2025 CRACK CS IT WITH DIVYA 177


STORAGE CLASS cont.. CRACK CS IT WITH DIVYA
3. static Storage Class
A static variable preserves its value between function calls.
Initialized only once and exists till program termination.
Global static variable → has internal linkage (not accessible outside the file).
In classes → one copy is shared among all objects.
Properties:
Scope: Local (for functions), File (for globals), Class (for data members)
Default Value: Zero
Memory Location: RAM
Lifetime: Till the end of the program

04-09-2025 CRACK CS IT WITH DIVYA 178


STORAGE CLASS cont.. CRACK CS IT WITH DIVYA
4. register Storage Class
Suggests storing a variable in a CPU register for faster access.
If no register is free, stored in RAM.
Address (& operator) cannot be used on register variables.
Properties:
Scope: Local
Default Value: Garbage
Memory Location: Register in CPU (or RAM if no free register)
Lifetime: Till the end of its scope

04-09-2025 CRACK CS IT WITH DIVYA 179


STORAGE CLASS cont.. CRACK CS IT WITH DIVYA
5.mutable Storage Class
Applies only to class/struct members.
Allows a member to be modified even in a const object or a const function.
Useful when some data members need to change while others stay constant.
Properties:
Scope: Class data member only
Default Value: Garbage
Memory Location: RAM
Lifetime: Lifetime of the object

04-09-2025 CRACK CS IT WITH DIVYA 180


Storage Scope/Vi Default Memory
CRACK CS IT WITH DIVYA
Keyword Lifetime
Class sibility Value Location
Automati Function
auto Local Garbage RAM
c Block
Whole
External extern Global Zero RAM
Program
Whole
Static static Local Zero RAM
Program
CPU
Function
Register register Local Garbage Register
Block
(or RAM)
Lifetime Class
Mutable mutable of the (Member Garbage RAM
Object s)

04-09-2025 CRACK CS IT WITH DIVYA 181


Classification of Datatypes CRACK CS IT WITH DIVYA

Data Type in
C++

Basic Data Derived Data User Defined


Types Types Data Types
int array class
float pointer structure
double reference union
char function Enumeration
bool
void
Arrays
CRACK CS
An array is a collection of elements of the same type placed inIT WITH DIVYA
contiguous memory locations. It allows you to store multiple values
under a single name and access them using an index. we can extract
the size using sizeof() operator
int main() {
int arr[] = {2, 4, 8, 12, 16};

// Accessing fourth element


cout << arr[3] << endl;

// updating first element


arr[0]=90;
cout << arr[0]<< endl;
cout << "Size of arr: " << sizeof(arr) << endl;
return 0;
}
04-09-2025 CRACK CS IT WITH DIVYA 183
Pointers CRACK CS IT WITH DIVYA

A pointer is a special variable that stores the memory address of another variable.
Instead of holding the actual value, it points to where the value is stored in memory.
Using pointers, we can:
Access data indirectly, perform dynamic memory allocation,Improve efficiency in
system-level programming.
The process of accessing the value present at the memory address pointed by the
pointer is called dereferencing.

& → Address-of operator (gives address).


* → Dereference operator (gives value at that address).
Directly printing a pointer → shows the address.
Using *pointer → gives the value stored at that address.

04-09-2025 CRACK CS IT WITH DIVYA 184


#include <iostream> CRACK CS IT WITH DIVYA
using namespace std;

int main() {
int x = 10; // normal variable
int *p = &x; // pointer storing address of x

cout << "Value of x: " << x << endl;


cout << "Address of x: " << p << endl; // pointer gives address
cout << "Value using pointer: " << *p << endl; // *p gives actual value

return 0;
}

04-09-2025 CRACK CS IT WITH DIVYA 185


Size of Pointers CRACK CS IT WITH DIVYA
The size of a pointer does not depend on the type of data it points to (e.g., int, char,
double, etc.).
Instead, it depends on the architecture of the system.
• 8 bytes for a 64-bit System
• 4 bytes for a 32-bit System Output:
int main() { 8
int *ptr1; 8
char *ptr2;
// Finding size using sizeof()
cout << sizeof(ptr1) << endl;
cout << sizeof(ptr2);
return 0;
}
04-09-2025 CRACK CS IT WITH DIVYA 186
CRACK CS IT WITH DIVYA
Special types of Pointers
Wild Pointer: When a pointer is created, it just contains a random address that may
or may not be valid. This type of pointer is called wild pointer.
NULL Pointer: A NULL pointer is a pointer that does not point to any valid memory
location but NULL. It is often used to initialize a pointer when you do not want it to
point to any object.
Void Pointers: A void pointer (void*) is a special type of pointer in C++ that has no
associated data type.It can hold address of any datatype. A void pointer cannot be
directly dereferenced
Dangling Pointer:A dangling pointer is a pointer that refers to memory which has
already been freed or is no longer valid.

04-09-2025 CRACK CS IT WITH DIVYA 187


CRACK CS IT WITH DIVYA
Operations allowed on pointer
➢Incrementing and Decrementing: ptr++,ptr--
➢Addition of Integer : ptr+5
➢Subtraction of Integer: ptr-5
➢Subtraction of Two Pointers of the Same Type: ptr2-ptr1
➢Comparison of Pointers and NULL

04-09-2025 CRACK CS IT WITH DIVYA 188


Pointer vs Reference CRACK CS IT WITH DIVYA

Pointers and reference are used to refer to other variables, but they operate in
different ways and have different behavior.

1. A pointer can be initialized after declaration, where as a reference must be


initialized at the time of declaration.

2. A pointer can be assigned NULL or nullptr,but reference cannot be null, it must


always refer to a valid object.

3. A pointer can be reassigned to point to different objects, a reference cannot be


reassigned once it is bound to an object.

04-09-2025 CRACK CS IT WITH DIVYA 189


User Defined Functions in C++
CRACK CS IT WITH DIVYA
A Function is a reusable block of code designed to perform a specific task.
Function Syntax in C++ return_type
function_name(parameter_list) {
// body of the function
}
Function Declaration vs Definition
declaration introduces the function to the compiler, while the definition provides the actual
implementation.
int add(int a, int b) {
// Declaration return a + b;
int add(int, int); }
When is Function Declaration Required?
Required if the function is defined after it's used (e.g., below main()).
Not required if the function is defined before
it's used — the compiler already knows it
04-09-2025 CRACK CS IT WITH DIVYA 190
Types of User-Defined Functions (Based on
CRACK CS IT WITH DIVYA
Parameters and Return Value)
No Parameters, No Return Value
Performs a task without taking input or returning a result.
Example: Displaying a message.
Parameters, No Return Value
Takes input but does not return a value.
Example: Displaying the sum of two numbers passed as arguments.
No Parameters, Return Value
Returns a value but does not take any input.
Example: Returning the current system time.
Parameters and Return Value
Takes input and returns a result.
Example: Calculating and returning the square of a number

04-09-2025 CRACK CS IT WITH DIVYA 191


Call by Value vs. Call by ReferenceCRACK CS IT WITH DIVYA
Functions can be invoked in two ways: Call by Value or Call by Reference.
Call by Value
➢A copy of the variable is passed to the function.
➢Changes do not affect the original variable.
➢Safe but less efficient for large data.
Call by Reference
➢A reference (alias) to the original variable is passed.
➢Changes do affect the original variable.
➢Efficient for memory and performance.

04-09-2025 CRACK CS IT WITH DIVYA 192


void increaseNumber(int num) { CRACK CS IT WITH DIVYA
num = num + 10; Output
cout << "Inside increaseNumber: " << num << endl; Inside increaseNumber: 15
} After increaseNumber: 5
void modifyNumber(int *num) { Inside modifyNumber: 15
num = num + 10; After modifyNumber: 15
cout << "Inside modifyNumber: " << num << endl;
}
int main() {
int a = 5, b = 5;
increaseNumber(&a);
cout << "After increaseNumber: " << a << endl;
modifyNumber(b);
cout << "After modifyNumber: " << b << endl;
return 0;
}

04-09-2025 CRACK CS IT WITH DIVYA 193


What is an Inline Function? CRACK CS IT WITH DIVYA

An inline function is a function where the compiler replaces the function call with
the function code during compilation. It’s used to reduce function call overhead,
especially for small, frequently used functions.
// Example
inline int square(int x) {
return x * x;
}
When you call square(5), the compiler replaces the call with 5 * 5.
When the Compiler May Ignore inline
CRACK CS IT WITH DIVYA

The compiler may ignore the inline keyword in these cases:


✓The function contains a loop
✓The function contains static variables
✓The function is recursive
✓The function has missing return for non-void
✓The function uses switch or goto
✓The function is too large
✓The function performs I/O operations

Syntax:
inline return_type function_name(parameters) {
// function body
}
Inline function cont.. CRACK CS IT WITH DIVYA
All functions defined inside a class are implicitly inline.
You can also declare inline inside a class and define it outside:

class A {
public:
inline int square(int x);
};
inline int A::square(int x) {
return x * x;
}
Virtual Functions Cannot Be Inlined
Virtual functions are resolved at runtime (dynamic binding) but
Inline happens at compile time
RECALL THIS PART AND CONTINUE CRACK CS IT WITH DIVYA

04-09-2025 CRACK CS IT WITH DIVYA 197


RECALL THIS PART AND CONTINUE Single Inheritance (WITH overriding)
CRACK CS IT WITH DIVYA

class Animal {
public:
void sound() { cout << "Generic animal
sound\n"; } This is function overriding, but runtime
}; polymorphism does not occur.
class Dog : public Animal { Since there is no base class pointer and no
public: virtual function, the function call is resolved at
void sound() { cout << "Dog barks\n"; compile
} time (early binding).
};
int main() { Child (Dog) redefines parent’s method sound (),
Animal a; So parent version is replaced when called from the
Dog d; child..
a.sound(); // Generic animal sound
d.sound(); } // Dog barks
04-09-2025 CRACK CS IT WITH DIVYA 198
CRACK CS IT WITH DIVYA
RUNTIME POLYMORPHISM
To achieve runtime polymorphism, the following conditions must be met:

➢Function overriding (derived class redefines base class function)

➢Base class pointer or reference (used to access derived objects)

➢Virtual function in the base class (enables dynamic dispatch)

04-09-2025 CRACK CS IT WITH DIVYA 199


class Animal { CRACK CS IT WITH DIVYA
public:
void sound() { cout << "Generic animal sound\n"; } };
class Dog : public Animal {
public: OUTPUT
void sound() { cout << "Dog barks\n"; } }; Generic animal sound
int main() { Generic animal sound
Animal a;
Dog d;
Animal* ptr;
ptr = &a;
ptr->sound(); // Calls Animal::sound()
ptr = &d;
ptr->sound(); // Still calls Animal::sound() because no virtual keyword
return 0; }

04-09-2025 CRACK CS IT WITH DIVYA 200


CRACK CS IT WITH DIVYA

ptr is a pointer of type Animal*.

When ptr points to a (an Animal object), calling


ptr->sound() calls Animal::sound().

When ptr points to d (a Dog object), calling ptr-


>sound() still calls Animal::sound() because the
sound() function is not virtual.

So, no runtime polymorphism occurs, and the


base class function is called both times.

04-09-2025 CRACK CS IT WITH DIVYA 201


Achieving Runtime Polymorphism with Virtual Functions
class Animal { CRACK CS IT WITH DIVYA
public:
virtual void sound() { cout << "Generic animal sound\n"; } // virtual function
};
Output
class Dog : public Animal { Dog barks
public:
void sound() Without virtual, the base
{ cout << "Dog barks\n"; } // overrides base function class version would be
}; called, even if the pointer
points to a derived object.
int main() {
Animal* ptr;
Dog d;
ptr = &d;
ptr->sound(); // Calls Dog's sound() at runtime due to virtual function
return
04-09-2025
0; } CRACK CS IT WITH DIVYA 202
What is the output of this program? CRACK CS IT WITH DIVYA

class Base {
public:
void print() {
cout << "Base Function" << endl;
} };
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
} };
int main() {
Derived derived1;
Base* ptr = &derived1;
ptr->print(); return 0;
}
04-09-2025 CRACK CS IT WITH DIVYA 203
What is the output of this program? CRACK CS IT WITH DIVYA

class Base {
public: Output
void print() { Base Function
cout << "Base Function" << endl;
} }; Since print() is not declared
class Derived : public Base { virtual in the base class,
public: compile-time binding (early
void print() { binding) occurs.
cout << "Derived Function" << endl;
} };
int main() {
Derived derived1;
Base* ptr = &derived1;
ptr->print(); return 0;
}
04-09-2025 CRACK CS IT WITH DIVYA 204
C++ virtual function CRACK CS IT WITH DIVYA

● A member function in the base class that you redefine in a derived class.

● It is declared using the virtual keyword.


● A 'virtual' is a keyword preceding the normal declaration of a function.
● When the function is made virtual, C++ determines which function is
to be invoked at the runtime based on the type of the object pointed
by the base class pointer.

04-09-2025 CRACK CS IT WITH DIVYA 205


CRACK CS IT WITH DIVYA
Rules of Virtual Function
● Virtual functions must be members of some class.
● Virtual functions cannot be static members.
● They can be a friend of another class.
● The prototypes of a virtual function of the base class and all the
derived classes must be identical.
● We cannot have a virtual constructor, but we can have a virtual
destructor

04-09-2025 CRACK CS IT WITH DIVYA 206


Why static functions can't be virtual:
CRACK CS IT WITH DIVYA

➢Virtual functions work with objects and need the hidden this pointer to decide
which object’s function to call at runtime.

➢Static functions belong to the class itself, not to any object.

➢Therefore, they don’t have a this pointer.

➢Since runtime polymorphism depends on the this pointer, static functions cannot
be virtual

04-09-2025 CRACK CS IT WITH DIVYA 207


Pure Virtual Functions and Abstract Base Classes
CRACK CS IT WITH DIVYA
➢A virtual function can sometimes be made to do nothing in the base class.
➢Such a function acts only as a placeholder, forcing derived classes to provide their
own implementation.
➢This is called a pure virtual function, and it is written as:
Virtual void draw()=0
▪ A class containing at least one pure virtual function is called an abstract base
class.
▪ Objects of an abstract base class cannot be created directly.
▪ Instead, it serves as a blueprint for derived classes, which must implement the
pure virtual function(s).

04-09-2025 CRACK CS IT WITH DIVYA 208


Pure Virtual Functions and Abstract Base
CRACK CS Classes
IT WITH DIVYA
cont..
▪ Abstract class can have constructors.
▪ We can have pointers and references of abstract class type.
▪ If we do not override the pure virtual function in derived class,then derived class
also becomes abstract class.

04-09-2025 CRACK CS IT WITH DIVYA 209


class Animal { CRACK CS IT WITH DIVYA
public: Explanation
virtual void sound() = 0; // pure virtual → no definition Animal is abstract, so you
}; cannot create objects of it.
class Dog : public Animal {
Dog overrides sound(), so it’s
public:
void sound() override { cout << "Dog barks\n"; } concrete and objects can be
}; created.
int main() Calling sound() through a
// Animal a; //Error: cannot create object of abstract class base pointer (Animal*) that
Dog d; // Allowed points to a Dog object results
Animal* ptr = &d; // base class pointer to derived object in runtime polymorphism

ptr->sound(); // Runtime polymorphism → "Dog barks"}

04-09-2025 CRACK CS IT WITH DIVYA 210


Interface in C++ CRACK CS IT WITH DIVYA

A class with only pure virtual functions is called an interface in C++.


You can't create an object of this class (it's abstract).
Any class that inherits this interface must override all pure virtual
functions.
class Animal { // Interface
in C++
public:
virtual void sound() = 0;
virtual void move() = 0;
};

04-09-2025 CRACK CS IT WITH DIVYA 211


Constructors CRACK CS IT WITH DIVYA

● Constructor is a member function of a class, whose name is same as the class


name.

● That is used to initialize the data members for an object of a class


automatically, when an object of the same class is created.

● Constructor is invoked at the time of object creation.

● They do not have a return type.

● Constructors can be overloaded.

04-09-2025 CRACK CS IT WITH DIVYA 212


3 Common Types of Constructors: CRACK CS IT WITH DIVYA
1. Default Constructor (no parameters) class Demo {
If no constructor is defined by the programmer, public:
the compiler automatically creates a default int x;
};
constructor. int main() {
This constructor: Demo d; // Default constructor called
▪ Takes no parameters (zero-argument) cout << d.x; // Garbage value,
▪ Is used to default-initialize data members uninitialized
▪ Also known as a zero-argument constructor return 0; }

04-09-2025 CRACK CS IT WITH DIVYA 213


class Test {
public: EXAMPLE USING CONSTRUCTOR
CRACK CS IT WITH DIVYA
int x;
string name;
OUTPUT
Test() // Constructor to initialize data members
x = 100
{ x = 100; name = C++
name = "C++"; }

void display() {
cout << "x = " << x << endl;
cout << "name = " << name << endl; } };

int main() {
Test t; // Constructor is called automatically
t.display(); // Display initialized values
return 0; }

04-09-2025 CRACK CS IT WITH DIVYA 214


CRACK CS IT WITH DIVYA
#include <iostream>
using namespace std;
No Output
// Class with no explicitly defined
Since no variables exist inside
constructors
the class, no garbage values
class A {
can appear.
public:
};
int main() {
// Creating object
A a;
return 0;
}

04-09-2025 CRACK CS IT WITH DIVYA 215


2. Parameterized Constructor in C++CRACK CS IT WITH DIVYA
A parameterized constructor allows values to be passed during object creation to
initialize data members.
Syntax: // Parameterized constructor
ClassName(parameters);

04-09-2025 CRACK CS IT WITH DIVYA 216


2. Parameterized Constructor in C++
class Student { CRACK CS IT WITH DIVYA
public:
int id; ID: 101, Name: Ameya
string name;
// Parameterized constructor
Student(int i, string n) {
id = i;
name = n; }

void display() {
cout << "ID: " << id << ", Name: " << name << endl;
} };

int main() {
Student s1(101, “Ameya"); // Passing values to constructor
s1.display();
return 0; }
04-09-2025 CRACK CS IT WITH DIVYA 217
Copy constructor CRACK CS IT WITH DIVYA

A copy constructor is a special constructor in C++ used to create a new object as a


copy of an existing object.
Syntax:
ClassName(const ClassName &obj);

04-09-2025 CRACK CS IT WITH DIVYA 218


class Student { CRACK CS IT WITH DIVYA
public:
int age = 18; // direct initialization
Student(const Student &s) { // copy constructor
cout << "Copy constructor called\n";
age = s.age; Output:18
} };

int main() {
Student s1; // object created, age = 18
Student s2 = s1; // copy constructor called
cout << s2.age;
}

04-09-2025 CRACK CS IT WITH DIVYA 219


Constructor Call Order in Inheritance
CRACK CS IT WITH DIVYA

• When you create an object of a derived class, the constructors are called in this
order:
• Base class constructor → Derived class constructor
• Even though you’re creating an object of the derived class, the base class
constructor runs first.

04-09-2025 CRACK CS IT WITH DIVYA 220


What is a Destructor? CRACK CS IT WITH DIVYA

A destructor is a special member function of a class that is executed


automatically when an object goes out of scope or is deleted.
▪ It is used to free resources (like memory, file handles, etc.).
▪ It has the same name as the class but is prefixed with a tilde (~).
▪ It cannot take arguments and cannot return a value.
Destructor Call Order in Inheritance
▪ When the object goes out of scope or is deleted, destructors are called in reverse
order:
▪ Derived class destructor → Base class destructor

04-09-2025 CRACK CS IT WITH DIVYA 221


Structure in C++ CRACK CS IT WITH DIVYA
A structure is a user-defined data type used to group variables of different data
types. Similar to an array, but can hold mixed types (int, char, float, etc.).
Syntax: struct StructureName {
type1 member1;
type2 member2;
.
.
typeN member;
};
Create variable: StructureName obj;
Access members: obj.member1;, obj.member2;

04-09-2025 CRACK CS IT WITH DIVYA 222


CRACK CS IT WITH DIVYA
EXAMPLE PROGRAM FOR STRUCTURE
struct Student {
int id;
char grade;
float marks;
};
int main() {
Student s = {7, 'B', 88.5};
cout << s.id << " " << s.grade << " " << s.marks;
return 0;
}

04-09-2025 CRACK CS IT WITH DIVYA 223


UNION CRACK CS IT WITH DIVYA

A union is also a user-defined data type, similar to struct.


But all members share the same memory, so only one member can
store a value at a time.
Syntax:
union UnionName {
type1 member1;
type2 member2;
.
.
typeN member;
};

04-09-2025 CRACK CS IT WITH DIVYA 224


union Data { CRACK CS IT WITH DIVYA
int intVal;
float floatVal;
char charVal; }; Output:
intVal: 100
int main() { floatVal: 12.34
Data d; charVal: A
d.intVal = 100; // store integer intVal after char:
cout << "intVal: " << d.intVal << endl;
(undefined)
d.floatVal = 12.34; // now float overwrites int
cout << "floatVal: " << d.floatVal << endl;

d.charVal = 'A'; // now char overwrites float


cout << "charVal: " << d.charVal << endl;
// notice: previous values are lost because same memory is reused
cout << "intVal after char: " << d.intVal << endl;
return 0; }
04-09-2025 CRACK CS IT WITH DIVYA 225
CRACK CS IT WITH DIVYA
TEMPLATES
Templates allow writing generic code that works with any data type. The idea is to
simply pass the data type as a parameter so that we don't need to write the same
code for different data types.
Templates can be defined using the keywords "template" and "typename" as
shown:
template <typename A, typename B, ...>
entity_definition

04-09-2025 CRACK CS IT WITH DIVYA 226


CRACK CS IT WITH DIVYA
#include <iostream>
using namespace std; OUTPUT
20
template <typename T> 5.5
T getMax(T a, T b) {
return (a > b) ? a : b;
}

int main() {
cout << getMax(10, 20) << endl; // int
cout << getMax(5.5, 2.3) << endl; // double
return 0;
}

04-09-2025 CRACK CS IT WITH DIVYA 227


CRACK CS IT WITH DIVYA
TEMPLATES cont..
In C++, templates are of three main types:
Function Templates
Used to write generic functions.
Example: getMax() that works for int, double, char, etc.
Class Templates
Used to write generic classes.
Example: Box<T> that can hold int, double, or char.
Variable Templates (introduced in C++14)
Used to define generic constants or variables.
Example: template <class T> T pi = T(3.14159);

04-09-2025 CRACK CS IT WITH DIVYA 228


File Handling Operations CRACK CS IT WITH DIVYA

File Handling Operations


➢Opening a file
➢Read/Write operations
➢Closing a file
File streams are provided in <fstream> header.
Syntax:
fstream str("filename.ext", mode);

04-09-2025 CRACK CS IT WITH DIVYA 229


File Opening Modes CRACK CS IT WITH DIVYA

▪ ios::in → Read
▪ ios::out → Write
▪ ios::binary → Binary mode
▪ ios::ate → Open the file and initially position at the end, but you can move it
▪ ios::app → Append at end always
▪ ios::trunc → Discard existing contents
Modes can be combined using |.

04-09-2025 CRACK CS IT WITH DIVYA 230


File Stream Classes CRACK CS IT WITH DIVYA

fstream → General input/output file stream


fstream file("data.txt", ios::in);
fstream file("data.txt", ios::out);
fstream file("data.txt", ios::in | ios::out);

ifstream → Input file stream (default: ios::in)


ofstream → Output file stream (default: ios::out)

04-09-2025 CRACK CS IT WITH DIVYA 231


What is Exception Handling? CRACK CS IT WITH DIVYA

A way to handle runtime errors without crashing the program.Uses try, catch, and
throw to separate normal code from error-handling code.
1. Throwing an Exception
When an error or unexpected situation occurs, the program uses the throw
keyword to signal an exception.
2. Catching an Exception
The program searches for a matching catch block to intercept and handle the
thrown exception.
3. Handling the Exception
The catch block contains the logic to respond to the error,
allowing the program to recover or terminate gracefully

04-09-2025 CRACK CS IT WITH DIVYA 232


CRACK CS IT WITH DIVYA
Exception Handling in C++
try-catch Block
It is an exception handling mechanism where the code that may cause
an exception is placed inside the try block and the code that handles
the exception is placed inside the catch block.
Syntax
try {
// Code that might throw an exception
}
catch (ExceptionType e) {
// exception handling code
}

04-09-2025 CRACK CS IT WITH DIVYA 233


Exception Handling in C++ CRACK CS IT WITH DIVYA

Throwing Exceptions
Throwing exception means returning some kind of value that represent
the exception from the try block. The throw keyword is used to throw
the exception.
try {
throw val
}
catch (ExceptionType e) {
// exception handling code
}

04-09-2025 CRACK CS IT WITH DIVYA 234


CRACK CS IT WITH DIVYA

THANK YOU

04-09-2025 CRACK CS IT WITH DIVYA 235

You might also like