0% found this document useful (0 votes)
6 views53 pages

Unit 1 CPP

The document outlines the fundamentals of Object-Oriented Programming (OOP) in C++, covering key concepts such as abstraction, encapsulation, inheritance, and polymorphism across five units. It includes detailed explanations of classes, constructors, operator overloading, function templates, exception handling, and file I/O, as well as the Standard Template Library (STL). The document serves as a comprehensive guide for understanding and implementing OOP principles in C++.

Uploaded by

ram5220008
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)
6 views53 pages

Unit 1 CPP

The document outlines the fundamentals of Object-Oriented Programming (OOP) in C++, covering key concepts such as abstraction, encapsulation, inheritance, and polymorphism across five units. It includes detailed explanations of classes, constructors, operator overloading, function templates, exception handling, and file I/O, as well as the Standard Template Library (STL). The document serves as a comprehensive guide for understanding and implementing OOP principles in C++.

Uploaded by

ram5220008
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

PROGRAMMING IN C++

UNIT-1 Fundamentals of Object-Oriented Programming in C++


Concepts of Object-Oriented Programming (OOP): abstraction, encapsulation,
polymorphism, inheritance, abstract classes.-Introduction to C++ language basics, I/O
mechanisms, and declarations.- Control structures: decision-making statements (if, else,
switch), loops (for, while, do–while), and jump statements (goto, break, continue).-Function
concepts: definitions, inline functions, function overloading.​​ ​ ​ ​

UNIT-2 Classes, Constructors, and Overloading


Defining classes and objects, object construction & destruction-Types of constructors: default,
parameterized, dynamic, copy constructor, and destructors-Operator overloading (unary,
binary, assignment, new/delete) and type conversion techniques-friend functions,
implicit/explicit constructors.​ ​ ​ ​ ​ ​ ​ ​

UNIT-3 Functions and Strings

Function templates and class templates enabling generic programming-Exception handling


mechanisms: try, catch, throw, rethrowing, exception specifications, and behavior of
terminate/unexpected.​ ​ ​ ​

UNIT-4 Inheritance, Polymorphism, and Runtime Typing


Types of inheritance: single, multilevel, multiple, hierarchical, hybrid; use of virtual base
classes and abstract classes-Polymorphism through virtual functions and pure virtual
functions-Run-time Type Identification (RTTI): typeid, dynamic_cast, cross casting, down
casting, and their relation to templates. ​ ​ ​ ​ ​ ​
UNIT-5 File I/O, Strings, and the STL​
Working with file streams: file modes, sequential & random access, binary and ASCII
files-Usage of I/O manipulators, namespaces, and the std namespace-String class operations
and attributes-Overview of the Standard Template Library (STL): containers (vectors, lists,
maps) and algorithms-Exception handling integrated with file I/O and STL usage.

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 1


UNIT–1 – Fundamentals of Object-Oriented Programming in C++

UNIT-1
Concepts of Object-Oriented Programming (OOP): abstraction, encapsulation,
polymorphism, inheritance, abstract classes.-Introduction to C++ language basics, I/O
mechanisms, and declarations.- Control structures: decision-making statements (if, else,
switch), loops (for, while, do–while), and jump statements (goto, break, continue).-Function
concepts: definitions, inline functions, function overloading.​​ ​ ​ ​

1. Object-Oriented Programming (OOP): Concepts & Principles

Object-Oriented Programming is a method of programming based on objects, which are


instances of classes.​
OOP focuses on mapping real-world entities into software components.

1.1 Why OOP? (Need & Advantages)

Limitations of Procedural Programming (C language)

●​ Data is exposed—less secure​

●​ Difficult to manage growing code bases​

●​ Low reusability​

●​ Poor ability to model real-world complex systems​

Advantages of OOP

●​ Better data security​

●​ Higher reusability through inheritance​

●​ Flexibility using polymorphism​

●​ Better maintainability​

●​ Encapsulation helps implement modular structure​

●​ Easier to solve real-world problems​

2. Basic Concepts of OOP (Explained in Depth)

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 2


2.1 Abstraction

Definition:

Abstraction means showing essential features while hiding internal details.

How it appears in C++:

●​ Classes​

●​ Abstract classes​

●​ Access specifiers​

●​ Header files​

Example:
class BankAccount {
private:
float balance; // hidden
public:
void deposit(float amt);
void withdraw(float amt);
};

Only functions are exposed; internal working is hidden.

🔹 How Abstraction is Achieved in C++


C++ provides abstraction mainly through:

1. Abstract Classes (using pure virtual functions)

2. Header files (function hiding)

🟦 1. Abstraction using Abstract Class


An abstract class is a class that contains at least one pure virtual function.

🔸 Pure Virtual Function


virtual void functionName() = 0;

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 3


This means the function has no implementation in the base class​
→ only the derived class gives the implementation.

✅ Example of Abstraction in C++


#include <iostream>

using namespace std;

// Abstract class

class Shape {

public:

// Pure virtual function

virtual void draw() = 0;

};

// Derived class 1

class Circle : public Shape {

public:

void draw() {

cout << "Drawing a Circle" << endl;

};

// Derived class 2

class Square : public Shape {

public:

void draw() {

cout << "Drawing a Square" << endl;

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 4


}

};

int main() {

Shape* s1 = new Circle();

Shape* s2 = new Square();

s1->draw();

s2->draw();

return 0;

✔ What the user sees?

●​ draw() is called → draws shape​

❌ What is hidden?
●​ How Circle is drawn​

●​ How Square is drawn​

This is abstraction.

🟦 2. Abstraction using Header Files


When you use functions like:

cout << "Hello";

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 5


You don't know:

●​ How printing is implemented​

●​ How buffering works​

●​ How the output stream works​

These are hidden inside <iostream>.

This is also abstraction in C++.

🟢 Real-Life Inspired Example in C++


Let’s use the ATM example using abstraction.

#include <iostream>

using namespace std;

class ATM {

public:

void withdrawMoney() {

enterPin();

processTransaction();

giveCash();

private:

void enterPin() {

cout << "PIN Entered..." << endl;

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 6


void processTransaction() {

cout << "Transaction Processing..." << endl;

void giveCash() {

cout << "Cash Dispatched!" << endl;

};

int main() {

ATM obj;

[Link](); // user sees only this function

return 0;

✔ Shown to user:

withdrawMoney()

❌ Hidden from user:


enterPin(), processTransaction(), giveCash()​
(marked as private, hidden = abstraction)

📝 Advantages of Abstraction in C++


Benefit Explanation

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 7


Reduces User sees only necessary details
complexity

Security Internal data/functions hidden

Flexibility Internal logic can change without affecting user

Reusability Common logic kept in abstract class

📚 Difference: Abstraction vs. Encapsulation (C++ context)


Abstraction Encapsulation

Hides implementation details Hides data

Achieved using abstract classes / private Achieved using private/protected


methods variables

Focus: What a class does Focus: How it does it

2.2 Encapsulation

Definition:

Encapsulation is the process of wrapping data and methods into a single unit, i.e., a class.

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 8


🟦 What is Encapsulation?
Encapsulation is one of the main principles of Object-Oriented Programming (OOP).​
It means wrapping data and the functions that operate on the data into a single unit
(class) and protecting the data from unauthorized access.

👉“Encapsulation
In simple words:​
= Data Hiding + Binding data with functions.”

Benefits:

●​ Data protection​

●​ Easier code maintenance​

●​ Implementation hiding​

Example:
class Student {
private:
int marks;
public:
void setMarks(int m) { marks = m; }
int getMarks() { return marks; }
};

🟢 Why Encapsulation?
●​ To hide sensitive data​

●​ To protect data from accidental modification​

●​ To control how data is accessed or changed​

●​ To make code secure and clean​

🟦 How Encapsulation is Achieved in C++?


C++ uses access specifiers to control access to data:

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 9


Access Meaning
Specifier

private data/functions accessible only inside


class

public accessible from anywhere

protected accessible inside class + derived


classes

Most often:

●​ Data → private​

●​ Methods → public (to access private data)​

🟣 Basic Example of Encapsulation (C++)


#include <iostream>

using namespace std;

class Student {

private:

int age; // hidden data

string name;

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 10


public:

void setAge(int a) { // setter

if(a > 0)

age = a;

int getAge() { // getter

return age;

};

int main() {

Student s;

[Link](20); // controlled access

cout << [Link]();

return 0;

✔ What is hidden?

age — cannot be accessed directly.

✔ What is allowed?

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 11


Use setAge() and getAge() to access the value safely.

This is encapsulation.

🟣 Real-Life Example (Medicine Bottle Analogy)


A medicine bottle:

●​ Contains tablets (data)​

●​ Has a cap (access control)​

●​ You cannot open it easily without permission​


→ Same in C++: private data is protected.​

🟢 Encapsulation Example with ATM (C++)


class ATM {

private:

int balance = 10000;

public:

void showBalance() {

cout << "Balance: " << balance << endl;

void withdraw(int amount) {

if(amount <= balance)

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 12


balance -= amount;

else

cout << "Insufficient Balance" << endl;

};

✔ balance is protected

No one can modify balance directly.

❌ Not allowed:
[Link] = 0; // Error: private

✔ Allowed:

[Link](500);

🟦 Why is Encapsulation Important?


Advantage Explanation

Data Protection Prevents unwanted changes

Security Sensitive info kept private

Modularity Code is clean and separated

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 13


Controlled Using setters & getters
Access

Easy Internal changes don’t affect outside


Maintenance code

🔵 Encapsulation vs. Abstraction (Quick Difference)


Encapsulation Abstraction

Hiding data Hiding implementation

Achieved using private/protected Achieved using abstract classes, interfaces

Focus: How data is accessed Focus: What object shows

Binding data + methods Showing essential features

2.3 Inheritance

Inheritance is the mechanism by which one class (derived class) acquires the properties of
another class (base class).

Types of Inheritance in C++:


Type Description

Single One base → One derived

Multiple One derived → Multiple base


classes

Multilevel Inheriting from a derived class

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 14


Hierarchical One base → Multiple derived

Hybrid Combination of two or more types

Example:
class A {
public:
void display() { cout << "A"; }
};

class B : public A {
public:
void show() { cout << "B"; }
};

🟦 What is Inheritance?
Inheritance is an OOP (Object-Oriented Programming) feature in C++ where one class
(child/derived class) can acquire the properties and behaviors of another class
(parent/base class).

👉“Inheritance
In simple words:​
allows code reusability by letting a new class use the features of an existing
class.”

🟢 Why Do We Use Inheritance?


●​ To reuse existing code​

●​ To avoid duplication​

●​ To create hierarchical relationships​

●​ To support polymorphism​

●​ To make programs cleaner and easier to maintain​

🟦 Basic Terminology

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 15


Term Meaning

Base Class (Parent) The class whose members are inherited

Derived Class (Child) The class that inherits from the base
class

🟣 Syntax of Inheritance in C++


class Derived : public Base {
// new features of Derived class
};

Access specifiers used:

●​ public​

●​ protected​

●​ private​

🟩 Example: Simple Inheritance


#include <iostream>
using namespace std;

class Animal { // Base class


public:
void eat() {
cout << "Eating..." << endl;
}
};

class Dog : public Animal { // Derived class


public:
void bark() {
cout << "Barking..." << endl;
}
};

int main() {
Dog d;
[Link](); // inherited from Animal
[Link](); // Dog's own function

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 16


}

✔ Dog can eat → because it inherited from Animal

✔ Dog has its own behaviour bark()

🟦 Types of Inheritance in C++


C++ supports 5 types:

1️⃣ Single Inheritance

One base → one derived

class A { };
class B : public A { };

2️⃣ Multilevel Inheritance

Grandparent → Parent → Child

class A { };
class B : public A { };
class C : public B { };

3️⃣ Multiple Inheritance

One derived class inherits from multiple base classes

class A { };
class B { };
class C : public A, public B { };

4️⃣ Hierarchical Inheritance

One base class → multiple derived classes

class A { };

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 17


class B : public A { };
class C : public A { };

5️⃣ Hybrid Inheritance

Combination of any two or more types​


(Example: Multiple + Multilevel)

🟦 Access Control in Inheritance


Base Class public protected private inheritance
Member inheritance inheritance

public public protected private

protected protected protected private

private ❌ never inherited ❌ ❌

🟦 Real-Life Example
Think of “Family Tree”:

●​ Grandfather → Father → Son​

●​ Son inherits features from both father and grandfather​

Similarly in C++:

●​ Class C inherits from class B​

●​ Class B inherits from class A​


→ C can use features of both A and B​

🟢 Advantages of Inheritance
Advantage Explanation

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 18


Code Reusability No need to rewrite the same code

Less Complexity Cleaner structure

Easy Maintenance Changes in base class reflect


everywhere

Supports Polymorphism Same function behaves differently

⭐ 1️⃣ Single Inheritance


One base class → one derived class

#include <iostream>
using namespace std;

class A { // Base class


public:
void displayA() {
cout << "This is class A" << endl;
}
};

class B : public A { // Derived class


public:
void displayB() {
cout << "This is class B" << endl;
}
};

int main() {
B obj;
[Link]();
[Link]();
}

⭐ 2️⃣ Multilevel Inheritance


A→B→C

#include <iostream>
using namespace std;

class A {
public:

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 19


void displayA() {
cout << "Class A" << endl;
}
};

class B : public A {
public:
void displayB() {
cout << "Class B" << endl;
}
};

class C : public B {
public:
void displayC() {
cout << "Class C" << endl;
}
};

int main() {
C obj;
[Link]();
[Link]();
[Link]();
}

⭐ 3️⃣ Multiple Inheritance


One class inherits from multiple base classes

#include <iostream>
using namespace std;

class A {
public:
void funA() {
cout << "From class A" << endl;
}
};

class B {
public:
void funB() {
cout << "From class B" << endl;
}
};

class C : public A, public B { // multiple inheritance

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 20


public:
void funC() {
cout << "From class C" << endl;
}
};

int main() {
C obj;
[Link]();
[Link]();
[Link]();
}

⭐ 4️⃣ Hierarchical Inheritance


One base class → multiple derived classes

#include <iostream>
using namespace std;

class A { // Base class


public:
void displayA() {
cout << "Base class A" << endl;
}
};

class B : public A { // Derived 1


public:
void displayB() {
cout << "Derived class B" << endl;
}
};

class C : public A { // Derived 2


public:
void displayC() {
cout << "Derived class C" << endl;
}
};

int main() {
B obj1;
C obj2;

[Link]();
[Link]();

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 21


[Link]();
[Link]();
}

⭐ 5️⃣ Hybrid Inheritance


Combination of multiple + multilevel

Example:

●​ A → B​

●​ A → C​

●​ C + B → D​

#include <iostream>
using namespace std;

class A {
public:
void displayA() {
cout << "Class A" << endl;
}
};

class B : public A {
public:
void displayB() {
cout << "Class B" << endl;
}
};

class C : public A {
public:
void displayC() {
cout << "Class C" << endl;
}
};

class D : public B, public C { // Hybrid inheritance


public:
void displayD() {
cout << "Class D" << endl;
}
};

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 22


int main() {
D obj;

[Link]();
[Link]();
[Link]();

// Note: displayA() is ambiguous due to two A copies


}

👉 If needed, we can remove ambiguity using virtual inheritance.

⭐ What is Polymorphism?
Polymorphism means one name, many forms.

👉A function
In simple words:​
or operator behaves differently in different situations.

Example in real life:

●​ The word "run" changes meaning:​

○​ run a race​

○​ run a program​

○​ run a machine​

In C++:

●​ The same function name can perform different tasks.​

⭐ Types of Polymorphism in C++


C++ supports two main types of polymorphism:

1️⃣ Compile-time Polymorphism

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 23


(also called Early Binding / Static Polymorphism)

Happens at compile time.

Includes:

●​ Function overloading​

●​ Operator overloading​

🔹 Function Overloading
Same function name, different parameters.

#include <iostream>
using namespace std;

class Add {
public:
int sum(int a, int b) { // 2 parameters
return a + b;
}
int sum(int a, int b, int c) { // 3 parameters
return a + b + c;
}
};

int main() {
Add obj;
cout << [Link](2, 3) << endl;
cout << [Link](1, 2, 3) << endl;
}

✔ Same function name → sum()​


✔ Different behavior → based on arguments

🔹 Operator Overloading
Redefining how operators work for user-defined types.

#include <iostream>
using namespace std;

class Sample {

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 24


public:
int x;

Sample(int a) { x = a; }

// operator overloading
Sample operator + (Sample obj) {
return Sample(x + obj.x);
}
};

int main() {
Sample s1(10), s2(20);
Sample s3 = s1 + s2;
cout << s3.x;
}

✔ + operator works on objects → polymorphism!

2️⃣ Runtime Polymorphism

(also called Late Binding / Dynamic Polymorphism)

Happens at runtime.

Achieved using:

●​ Inheritance​

●​ Function overriding​

●​ Virtual functions​

🔹 Function Overriding (Runtime Polymorphism)


Same function name + same parameters​
→ But defined in both base and derived classes.

Using Virtual Functions


#include <iostream>
using namespace std;

class Animal {

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 25


public:
virtual void sound() { // virtual function
cout << "Animal makes sound" << endl;
}
};

class Dog : public Animal {


public:
void sound() {
cout << "Dog barks" << endl;
}
};

int main() {
Animal* a;
Dog d;

a = &d; // base pointer points to derived object


a->sound(); // calls Dog's sound() → runtime polymorphism
}

✔ Virtual function ensures correct function is called at runtime​


✔ Even though pointer is of type Animal*, Dog’s version is executed

⭐ Difference Between Compile-time and Runtime Polymorphism


Feature Compile-time Runtime

Binding time Compile time Runtime

Techniques Function overloading, Operator Function overriding


overloading

Speed Faster Slower

Uses Changing behavior by parameters Changing behavior by


inheritance

⭐ Real-World Analogy
TV Remote Example:

●​ Same "power" button​

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 26


●​ Works differently on different devices​
(AC, TV, Projector, Set-top box)​

Same button → different behavior → Polymorphism

⭐ Exam-Friendly Definition
Polymorphism in C++ is the ability of a function, operator, or object to take multiple
forms. It allows the same function name to behave differently depending on the context.
It is of two types: compile-time polymorphism (function/operator overloading) and
runtime polymorphism (function overriding using virtual functions).

2.5 Abstract Classes

●​ A class containing at least one pure virtual function.​

●​ Cannot create objects from it.​

●​ Used to design interfaces.​

Example:
class Shape {
public:
virtual void draw() = 0; // pure virtual
};

⭐ What Are Abstract Classes?


An abstract class is a class that cannot be instantiated (you cannot create objects of it).​
It is designed to be a base class, providing a blueprint for derived classes.

👉 Its main purpose is to enforce some functions that must be implemented by child
classes.

⭐ Key Feature: Pure Virtual Function


A class becomes abstract when it has at least one pure virtual function.

Syntax:

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 27


virtual void functionName() = 0;

Meaning:

●​ The function has no body in the base class​

●​ Derived classes must define it​

⭐ Why Abstract Classes?


●​ To provide a common interface for all derived classes​

●​ To hide implementation and show only essential features → abstraction​

●​ To force derived classes to implement some functions​

●​ Helps in runtime polymorphism​

⭐ Simple Example of Abstract Class (C++)


#include <iostream>
using namespace std;

class Shape { // Abstract class


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

class Circle : public Shape {


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

class Square : public Shape {


public:
void draw() {
cout << "Drawing Square" << endl;
}
};

int main() {

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 28


Shape* s;

Circle c;
Square sq;

s = &c;
s->draw(); // Circle version

s = &sq;
s->draw(); // Square version
}

✔ You cannot do:


Shape s; // ❌ Error: abstract class cannot create objects
✔ You can do:
Shape* ptr; // allowed

Because the pointer does NOT create an object.

⭐ Characteristics of Abstract Classes


Feature Explanation

Cannot create objects Abstract class only acts as a base class

Can contain constructors Yes, but object creation must happen in child
class

Can have both pure virtual and normal Yes


functions

Child class must override pure virtual Otherwise, child also becomes abstract
functions

Used for runtime polymorphism Yes

⭐ Abstract Class With Both Normal & Pure Virtual Functions


class Animal {
public:
void sleep() {

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 29


cout << "Sleeping..." << endl; // normal function
}

virtual void sound() = 0; // pure virtual


};

✔ Normal functions → Already implemented​


✔ Pure virtual functions → Must be implemented by derived class

⭐ Why Use Pure Virtual Functions?


They force derived classes to provide specific features.

Example:​
Every animal makes sound → but sound is different

●​ Dog → bark​

●​ Cat → meow​

●​ Cow → moo​

So the base class provides structure, but derived classes provide implementation.

⭐ Real-World Analogy
Think of a template form:

●​ The structure (fields) is fixed​

●​ But you must fill in your own details​

Abstract class = form template​


Derived class = filled form

⭐ Advantages of Abstract Classes


●​ Enforces consistent design​

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 30


●​ Achieves abstraction​

●​ Supports polymorphism​

●​ Reduces code duplication​

●​ Provides a flexible and scalable structure​

⭐ Important Notes for Exams


✔ Abstract class = defined using pure virtual function

✔ Cannot be instantiated

✔ Used to create a common interface

✔ Child class must override pure virtual functions

✔ May contain:

●​ constructors​

●​ destructors​

●​ normal functions​

●​ member variables​

⭐ Simple Definition (2 Mark Answer)


An abstract class in C++ is a class that contains at least one pure virtual function and
cannot be instantiated. It provides a blueprint for derived classes and supports
abstraction and polymorphism.

3. Introduction to C++ Language Basics

3.1 Tokens in C++

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 31


Smallest units in a program:

●​ Keywords (int, class, while)​

●​ Identifiers (sum, student1)​

●​ Constants (10, 'a', 3.14)​

●​ Operators (+, -, *, /)​

●​ Punctuation (;, {, })​

3.2 Structure of a C++ Program


#include <iostream>
using namespace std;

int main() {
cout << "Hello C++";
return 0;
}

Explanation of each component

●​ #include <iostream> – Library file for I/O​

●​ using namespace std; – Allows usage of standard library names​

●​ main() – Starting point​

●​ cout – Print to screen​

●​ return 0; – Successful termination​

3.3 C++ I/O Mechanism

cout – output stream


cout << "Total Marks = " << marks;

cin – input stream

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 32


int age;
cin >> age;

3.4 Variable Declarations


int a;
float salary;
char grade;
bool isActive;

4. Control Structures in C++ (Detailed)

⭐ What Are Control Structures in C++?


Control structures are statements that control the flow of execution in a program.​
They allow you to make decisions, repeat tasks, and change the order in which statements
run.

👉 Without control structures, a program would run line-by-line only.

⭐ Types of Control Structures


C++ has three main types:

1.​ Sequential Control Structure​

2.​ Selection (Decision-Making) Control Structure​

3.​ Iteration (Looping) Control Structure​

1️⃣ Sequential Control Structure

This is the default flow.​


Statements execute one after another in the order they appear.

Example:
int a = 10;
int b = 20;

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 33


int c = a + b;
cout << c;

✔ Executed step-by-step​
✔ No decision making​
✔ No loops

2️⃣ Selection (Decision-Making) Control Structure

Used to make choices based on conditions.

C++ provides:

✔ if

✔ if-else

✔ else-if ladder

✔ nested if

✔ switch

🔹 if Statement
if (age >= 18) {
cout << "Eligible to vote";
}

🔹 if-else Statement
if (num % 2 == 0) {
cout << "Even";
} else {
cout << "Odd";
}

🔹 else-if Ladder
if (marks >= 90)
cout << "A grade";

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 34


else if (marks >= 75)
cout << "B grade";
else if (marks >= 50)
cout << "C grade";
else
cout << "Fail";

🔹 Nested if
if (a > 0) {
if (a % 2 == 0)
cout << "Positive Even";
}

🔹 switch Case
Used when you have multiple specific values.

int choice = 2;

switch (choice) {
case 1: cout << "Start"; break;
case 2: cout << "Stop"; break;
case 3: cout << "Exit"; break;
default: cout << "Invalid";
}

✔ Faster than multiple if-else​


✔ Works only with integer/char/enums

3️⃣ Iteration (Looping) Control Structure

Used to repeat a block of code multiple times.

C++ provides:

✔ for loop

✔ while loop

✔ do-while loop

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 35


✔ nested loops

🔹 for Loop
Used when number of iterations is known.

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


cout << i << " ";
}

🔹 while Loop
Used when number of iterations is unknown.

int i = 1;

while (i <= 5) {
cout << i << " ";
i++;
}

🔹 do-while Loop
Runs at least once because condition checked at the end.

int i = 1;

do {
cout << i << " ";
i++;
} while (i <= 5);

⭐ Jump Statements in C++ (Extra Control)


These also control flow inside loops:

✔ break

●​ exits loop or switch​

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 36


✔ continue

●​ skips current iteration​

✔ goto (rarely used, not recommended)

●​ jumps to a labeled statement​

🔹 Example: break
for(int i=1; i<=10; i++) {
if (i == 5)
break;
cout << i << " ";
}

🔹 Example: continue
for(int i=1; i<=5; i++) {
if (i == 3)
continue;
cout << i << " ";
}

⭐ Short Summary (Exam Answer)


Control structures in C++ are constructs that determine the flow of execution of a
program. They are classified into:

1.​ Sequential – statements executed in order.​

2.​ Selection – decision-making (if, if-else, switch).​

3.​ Iteration – repeating statements (for, while, do-while).​

They make programs dynamic, flexible, and logical.

5. Function Concepts (Expanded)

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 37


Definition:

A function is a named block of code used to perform a task.

5.1 Function Components

●​ Function prototype​

●​ Function definition​

●​ Function call​

⭐ FUNCTION CONCEPTS IN C++ (Detailed Explanation)


A function is a block of code that performs a specific task.​
It helps in code reusability, modularity, and better program structure.

⭐ 1. Why Functions? (Advantages)


●​ Avoids code repetition​

●​ Makes program modular​

●​ Easier to debug and maintain​

●​ Improves readability​

●​ Can reuse the function anywhere​

⭐ 2. Types of Functions in C++


C++ supports two main types:

✔ 1. Built-in (Library) Functions

Already available in C++ libraries.​


Example:

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 38


●​ sqrt(), pow(), strlen(), cout, cin

✔ 2. User-defined Functions

Created by the programmer.

Example:

void display() {

cout << "Hello";

⭐ 3. Function Syntax
return_type function_name(parameter_list) {

// body of function

Example:

int add(int a, int b) {

return a + b;

Here

●​ int → return type​

●​ add → function name​

●​ (int a, int b) → parameters​

●​ return a + b → return statement​

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 39


⭐ 4. Function Components (Very Important)
Function Declaration (Prototype)​
Tells compiler about function name, return type, parameters.​

Example:​

int add(int, int);

Function Definition​
Contains the actual code.​

Function Call​
When you tell the function to execute.​

⭐ 5. Types of User-Defined Functions


✔ 1. Function with No Arguments and No Return Value

void hello() {

cout << "Hello";

int main() {

hello();

✔ 2. Function with Arguments but No Return Value

void add(int a, int b) {

cout << a + b;

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 40


✔ 3. Function with No Arguments but Returns Value

int getNumber() {

return 10;

✔ 4. Function with Arguments and Return Value

int mul(int a, int b) {

return a * b;

⭐ 6. Call by Value vs Call by Reference


✔ Call by Value

●​ Copy of the variable is passed​

●​ Changes inside function do NOT affect original​

Example:

void change(int x) {

x = 10;

✔ Call by Reference

●​ Address of variable is passed​

●​ Changes made inside the function affect the original​

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 41


Example:

void change(int &x) {

x = 10;

⭐ 7. Default Arguments
If argument is not passed, default value is used.

int add(int a, int b = 5) {

return a + b;

cout << add(10); // Output: 15

⭐ 8. Function Overloading (Polymorphism)


Same function name, different parameters.

int area(int a) { return a * a; } // square

int area(int l, int b) { return l * b; } // rectangle

⭐ 9. Inline Functions
Used for small functions to increase performance.

inline int cube(int x) {

return x * x * x;

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 42


}

⭐ 10. Recursive Functions


A function calling itself.

Example: factorial

int fact(int n) {

if (n == 0) return 1;

return n * fact(n - 1);

⭐ 11. Function Overriding (OOP)


Occurs in inheritance when a derived class has the same function as base class.

class A {

public:

void display(){ cout<<"A"; }

};

class B : public A {

public:

void display(){ cout<<"B"; }

};

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 43


⭐ 12. Library Functions in C++
Found in header files like:

Header Functions

<math.h> sqrt(),
pow(
),
abs()

<string.h> strlen(),
strcp
y()

<ctype.h> isalpha()
,
isdigi
t()

<iostream> cin, cout

⭐ Complete Simple Example


#include <iostream>

using namespace std;

int add(int x, int y) { // function definition

return x + y;

int main() {

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 44


int a = 5, b = 10;

cout << "Sum = " << add(a, b); // function call

⭐ 2-Mark Definition
A function in C++ is a self-contained block of code that performs a specific task and can
be reused throughout a program. It consists of a function declaration, definition, and call.

⭐ 5-Mark Answer Summary


●​ Definition​

●​ Need/Advantages​

●​ Types of functions​

●​ Syntax​

●​ Components (prototype, call, definition)​

●​ Call by value/reference​

●​ Function overloading​

●​ Recursive function​

●​ Inline function​

●​ Examples​

REVISION PROGRAMS

✔ Abstraction – Program 1
#include <iostream>
using namespace std;

class Calculator {

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 45


private:
int a, b;

public:
void getData(int x, int y) {
a = x; b = y;
}
int add() { return a + b; }
};

int main() {
Calculator c;
[Link](5, 3);
cout << "Sum = " << [Link]();
}

✔ Abstraction – Program 2
#include <iostream>
using namespace std;

class Area {
public:
float rectangle(float l, float b) {
return l * b;
}
};

int main() {
Area a;
cout << "Area = " << [Link](5.5, 4.2);
}

✔ Encapsulation – Program 1
#include <iostream>
using namespace std;

class Student {
private:
int age;

public:
void setAge(int a) { age = a; }
int getAge() { return age; }
};

int main() {
Student s;

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 46


[Link](20);
cout << "Age = " << [Link]();
}

✔ Encapsulation – Program 2
#include <iostream>
using namespace std;

class Account {
private:
float balance = 0;

public:
void deposit(float amt) {
if (amt > 0) balance += amt;
}
float getBalance() { return balance; }
};

int main() {
Account a;
[Link](500);
cout << "Balance = " << [Link]();
}

✔ Polymorphism – Program 1 (Function Overloading)


#include <iostream>
using namespace std;

class Display {
public:
void show(int x) { cout << "Integer: " << x << endl; }
void show(string s) { cout << "String: " << s << endl; }
};

int main() {
Display d;
[Link](25);
[Link]("Hello");
}

✔ Polymorphism – Program 2 (Virtual Function)


#include <iostream>
using namespace std;

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 47


class Animal {
public:
virtual void sound() { cout << "Animal sound" << endl; }
};

class Dog : public Animal {


public:
void sound() { cout << "Dog barks" << endl; }
};

int main() {
Animal* a;
Dog d;
a = &d;
a->sound();
}

✔ Inheritance – Program 1 (Single Inheritance)


#include <iostream>
using namespace std;

class A {
public:
void displayA() { cout << "Class A" << endl; }
};

class B : public A {
public:
void displayB() { cout << "Class B" << endl; }
};

int main() {
B obj;
[Link]();
[Link]();
}

✔ Inheritance – Program 2 (Multilevel)


#include <iostream>
using namespace std;

class A {
public: void funA() { cout << "A" << endl; } };

class B : public A {

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 48


public: void funB() { cout << "B" << endl; } };

class C : public B {
public: void funC() { cout << "C" << endl; } };

int main() {
C obj;
[Link]();
[Link]();
[Link]();
}

✔ Abstract Class – Program 1


#include <iostream>
using namespace std;

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

class Circle : public Shape {


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

int main() {
Shape* s = new Circle();
s->draw();
}

✔ Abstract Class – Program 2


#include <iostream>
using namespace std;

class Vehicle {
public:
virtual void start() = 0;
};

class Car : public Vehicle {


public:
void start() { cout << "Car Starts" << endl; }
};

int main() {

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 49


Car c;
[Link]();
}

✔ Basics – Program 1: Input / Output


#include <iostream>
using namespace std;

int main() {
int a;
cout << "Enter a number: ";
cin >> a;
cout << "You entered: " << a;
}

✔ Basics – Program 2: Variable Declarations


#include <iostream>
using namespace std;

int main() {
int a = 10, b = 20;
cout << "Sum = " << a + b;
}

✔ Decision-Making – Program 1 (If-Else)


#include <iostream>
using namespace std;

int main() {
int n;
cin >> n;
if (n > 0) cout << "Positive";
else cout << "Non-positive";
}

✔ Decision-Making – Program 2 (Switch)


#include <iostream>
using namespace std;

int main() {
int a, b, ch;
cin >> a >> b >> ch;

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 50


switch (ch) {
case 1: cout << a + b; break;
case 2: cout << a - b; break;
default: cout << "Invalid";
}
}

✔ Loop – Program 1 (For loop)


#include <iostream>
using namespace std;

int main() {
for (int i = 1; i <= 10; i++)
cout << i << " ";
}

✔ Loop – Program 2 (While loop sum)


#include <iostream>
using namespace std;

int main() {
int n = 5, sum = 0;
while (n > 0) {
sum += n;
n--;
}
cout << "Sum = " << sum;
}

✔ Jump Statement – Program 1 (Continue)


#include <iostream>
using namespace std;

int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) continue;
cout << i << " ";
}
}

✔ Jump Statement – Program 2 (Goto)

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 51


#include <iostream>
using namespace std;

int main() {
int n = 1;
start:
cout << n << " ";
n++;
if (n <= 5) goto start;
}

4.1 Function Definition

✔ Function – Program 1
#include <iostream>
using namespace std;

int add(int a, int b) {


return a + b;
}

int main() {
cout << add(5, 3);
}

4.2 Inline Function

✔ Inline – Program 2
#include <iostream>
using namespace std;

inline int square(int x) {


return x * x;
}

int main() {
cout << square(6);
}

4.3 Function Overloading

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 52


✔ Overloading – Program 1
#include <iostream>
using namespace std;

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


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

int main() {
cout << add(5, 3) << endl;
cout << add(2.5f, 1.5f);
}

✔ Overloading – Program 2
#include <iostream>
using namespace std;

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


void display(char c) { cout << "Character: " << c << endl; }

int main() {
display(10);
display('A');
}

Programming in C++/ Prepared by B Kalpana -HOD CSE ​ ​ ​ ​ 53

You might also like