0% found this document useful (0 votes)
4 views47 pages

CPP Full Notes

The document provides comprehensive notes on C++ programming, focusing on programming paradigms, particularly Object Oriented Programming (OOP), and its key concepts such as classes, objects, data types, and encapsulation. It details the differences between C, C++, and Java, emphasizing the features of C++ like constructors and destructors. Additionally, it includes examples and explanations of member functions, data hiding, and the structure of a C++ program.

Uploaded by

pawa912899
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)
4 views47 pages

CPP Full Notes

The document provides comprehensive notes on C++ programming, focusing on programming paradigms, particularly Object Oriented Programming (OOP), and its key concepts such as classes, objects, data types, and encapsulation. It details the differences between C, C++, and Java, emphasizing the features of C++ like constructors and destructors. Additionally, it includes examples and explanations of member functions, data hiding, and the structure of a C++ program.

Uploaded by

pawa912899
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

rd

C++ Notes AKU BCA 3 Semester


UNIT - 1

Introduction to Programming Paradigms


Programming paradigms are the styles or approaches of programming that define how a
program is written and executed. It explains how data is handled and how instructions are
structured in a program.

There are different programming paradigms, but in BCA syllabus the main focus is on Object
Oriented Programming (OOP), which is supported by C++ and Java.

Procedural Programming
Procedural programming is a programming approach where a program is divided into functions.
Data and functions are treated separately. The main focus is on procedure or function
execution.

Example language: C

In procedural programming, there is no concept of class or object.

Object Oriented Programming (OOP)


Object Oriented Programming is a programming paradigm where a program is designed using
objects. It combines data and functions into a single unit called an object.

Example languages: C++, Java

OOP is based on real-world entities.

Concept of Object
An object is a real-world entity that has state and behavior.

State means the data or variables of an object.


Behavior means the functions or methods of an object.

An object is an instance of a class, which means it is created from a class.

An object is a physical entity and it occupies memory.

Example:
Mobile phone is an object.
Its data can be brand and price.
Its behavior can be calling and messaging.

Concept of Class
A class is a user-defined data type used to create objects. It acts as a blueprint or template of
an object.

A class defines:

 What data an object will have


 What functions an object can perform

A class is a logical entity and does not occupy memory.

Memory is allocated only when an object of the class is created.

Object as Variable of Class


An object is treated as a variable whose data type is a class.

Just like:

int a;

Similarly in OOP:

Student s1;

Here, Student is a class (data type) and s1 is an object (variable).

Multiple objects of the same class can be created, and each object has separate memory.

Concept of Data Type


A data type specifies:

 The type of data to be stored


 The size of memory required
 The operations that can be performed on data

Data types are necessary so that the computer can understand how to store and process data.
Primitive (Built-in) Data Types
Primitive data types are basic data types provided by the programming language.

int
Used to store whole numbers.
Example: int a = 10;

float
Used to store decimal numbers.
Example: float b = 2.5;

double
Used to store large decimal numbers with high precision.
Example: double d = 10.5678;

char
Used to store single character.
Example: char c = 'A';

These data types are common in C, C++ and Java.

Derived Data Types


Derived data types are formed using primitive data types.

Array
Used to store multiple values of the same data type.
Example: int arr[5];

Pointer
Used to store the address of another variable.
Example: int *p;

Pointers are available in C and C++, but not directly in Java.

User Defined Data Types


User-defined data types are created by the programmer.

struct
Used to store different types of data together.
Available in C and C++.

union
All members share the same memory location.
enum
Used to define named constant values.

class
Used to create objects in OOP.

Class as Data Type


In Object Oriented Programming, a class itself acts as a data type. An object is a variable of
that class type.

Example:

Student s1;

C vs C++ vs Java (Core Difference)


C follows procedural programming and does not support class and object.
C++ supports both procedural and object oriented programming.
Java is a pure object oriented programming language.

Class and object are available in C++ and Java, but not in C.
Pointers are present in C and C++, but not in Java.

Exam Ready Lines (Must Write)


Class is a blueprint of an object.
Object is an instance of a class.
Class is a logical entity.
Object occupies memory.
Class is a user-defined data type.

Structure and Class – Basic Introduction


Structure and class are user-defined data types used to group data members (variables) and
member functions under one name.
Structure is mainly used in procedural programming, while class is used in object oriented
programming.

Difference Between Structure and Class in Terms of Access to Members


The main difference between structure and class is the default access control.

In a structure, all members are public by default.


This means structure members can be accessed from anywhere in the program.
In a class, all members are private by default.
This means class members cannot be accessed directly from outside the class.

This difference makes class more secure than structure.

Structure Example (Access to Members)

struct Student {
int roll;
float marks;
};

Student s1;
[Link] = 10; // allowed
[Link] = 80.5; // allowed

Here, data members are accessed directly, because structure members are public.

Class Example (Access to Members)

class Student {
int roll;
float marks;
};

Student s1;
// [Link] = 10; ❌ not allowed

Here, members are private by default, so direct access is not allowed.

Public Member of a Class


Public members of a class are those members which can be accessed from outside the class.

Public members are declared using the keyword public.

Public members are generally used to provide controlled access to private data.

Example:

class Student {
public:
int roll;
};
Private Member of a Class
Private members of a class are those members which cannot be accessed directly from outside
the class.

Private members are used to hide data and provide data security.

By default, all class members are private.

Example:

class Student {
private:
int roll;
};

Accessing Private Members Using Public Functions


Private data members can be accessed using public member functions.

Example:

class Student {
private:
int roll;
public:
void setRoll(int r) {
roll = r;
}
int getRoll() {
return roll;
}
};

This concept is called data hiding.

Data Members
Data members are the variables declared inside a class or structure.

They represent the state of an object.

Example:

int roll;
float marks;

Each object has its own copy of data members.


Member Functions
Member functions are the functions defined inside a class or structure.

They represent the behavior of an object.

Member functions can access both private and public data members.

Example:

void display() {
cout << roll;
}

Data and Function Members in Structure


In structure, data members and functions are public by default.

Structure is mainly used to store data, not to provide security.

Encapsulation is not strict in structure.

Data and Function Members in Class


In class, data members are usually private and functions are public.

This supports encapsulation and data hiding.

Class is used when security and abstraction are required.

C vs C++ vs Java Comparison


Structure is available in C and C++, but not in Java.
Class is available in C++ and Java, but not in C.

C does not support access specifiers like public and private.


C++ and Java support public, private and protected.

Key Difference Summary (Exam Lines)


Structure members are public by default.
Class members are private by default.
Structure provides less security.
Class provides data hiding and security.
Class supports full object oriented programming.

Characteristics of Object Oriented Programming (OOP)


Object Oriented Programming is a programming paradigm that focuses on objects rather than
functions. OOP has several important characteristics which help in building secure, modular
and reusable programs.
The most important characteristics are Data Hiding, Encapsulation and Data Security.

Data Hiding
Data hiding is the process of restricting direct access to data members of a class from outside
the class.

In data hiding, the internal details of data are hidden, and only necessary information is
provided to the outside world.

Data hiding is achieved by using private access specifier in a class.

Why Data Hiding is Needed


Data hiding prevents unauthorized access to data.
It protects data from accidental modification.
It makes the program more secure and reliable.

Example of Data Hiding

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

Here, marks is hidden from outside access and can be accessed only through public functions.
Encapsulation
Encapsulation is the process of binding data members and member functions together into a
single unit.

In encapsulation, data and functions that operate on that data are wrapped inside a class.

Encapsulation is a core concept of OOP.

Why Encapsulation is Important


Encapsulation improves code organization.
It helps in data hiding.
It makes the program easy to maintain and modify.

Example of Encapsulation

class Student {
private:
int roll;
public:
void setRoll(int r) {
roll = r;
}
int getRoll() {
return roll;
}
};

Here, data and functions are combined inside the class, which is encapsulation.

Difference Between Data Hiding and Encapsulation


Encapsulation is the mechanism of wrapping data and functions together.
Data hiding is the result of encapsulation.

Encapsulation focuses on structure.


Data hiding focuses on security.

Data Security
Data security in OOP means protecting data from misuse and unauthorized access.

Data security ensures that data can be accessed only by authorized parts of the program.
Data security is achieved using:

 Access specifiers (private, public, protected)


 Data hiding
 Encapsulation

How OOP Provides Data Security


Private data members restrict direct access.
Public methods provide controlled access.
Only valid operations are allowed on data.

Example Showing Data Security

class BankAccount {
private:
double balance;
public:
void deposit(double amount) {
balance += amount;
}
double getBalance() {
return balance;
}
};

Here, balance cannot be changed directly, ensuring data security.

C vs C++ vs Java (Related to OOP Characteristics)


C does not support data hiding and encapsulation.
C++ supports data hiding and encapsulation using classes.
Java provides strong data security because everything is inside classes.

Java is considered more secure than C++ because it does not use pointers directly.

Exam Ready Lines (Must Write)


Data hiding protects data from direct access.
Encapsulation binds data and functions together.
Data security ensures safe access to data.
Encapsulation is a technique, data hiding is its outcome.
OOP provides better security than procedural programming.
UNIT – 2(Basics of C++)
Basics of C++
C++ is an object oriented programming language developed as an extension of C.
It supports procedural as well as object oriented programming.
C++ uses classes and objects to implement OOP concepts.

Structure of a C++ Program


A C++ program is divided into different parts, and each part has a specific role.

The basic structure of a C++ program includes:

 Header files
 Namespace
 Main function
 Class definition
 Function definitions

Header Files
Header files contain predefined functions and declarations.
They are included using #include.

Example:

#include <iostream>

Namespace in C++
A namespace is used to avoid name conflict between identifiers.
The keyword using is used to access members of a namespace.

Example:

using namespace std;

This allows us to use cout and cin without writing std::.

Main Function
The main() function is the entry point of a C++ program.
Execution of the program starts from main().
Example:

int main() {
return 0;
}

Declaring a Class
A class is declared using the keyword class.
It contains data members and member functions.

Example:

class Student {
int roll;
float marks;
};

By default, all members of a class are private.

Creating Objects
An object is created by using the class name as a data type.

Example:

Student s1;

Here:

 Student → class (data type)


 s1 → object (variable)

Each object has its own separate memory.

Member Functions
Member functions are the functions declared inside a class.
They are used to perform operations on data members.

Member functions can be defined:

 Inside the class


 Outside the class
Defining Member Functions Inside a Class
When a member function is defined inside a class, it is automatically treated as inline.

Example:

class Student {
public:
void show() {
cout << "Hello Student";
}
};

This is simple and easy for small functions.

Defining Member Functions Outside a Class


Member functions can also be defined outside the class using the scope resolution operator
(::).

Example:

class Student {
public:
void show();
};

void Student::show() {
cout << "Hello Student";
}

This method is used for large and complex functions.

Scope Resolution Operator (::)


The scope resolution operator is used to define a member function outside the class.

It tells the compiler that the function belongs to a specific class.

Keyword using
The using keyword is used to access namespace members.

Example:

using namespace std;


Without using, we must write:

std::cout << "Hello";

Complete Simple C++ Program

#include <iostream>
using namespace std;

class Student {
public:
void show() {
cout << "Welcome to C++";
}
};

int main() {
Student s1;
[Link]();
return 0;
}

C vs C++ vs Java (Related to Basics)


C does not support classes and objects.
C++ supports classes and objects.
Java supports classes and objects but does not use header files.

C++ allows both procedural and object oriented programming,


Java supports only object oriented programming.

Exam Ready Lines (Must Write)


C++ is an extension of C.
Class is declared using the keyword class.
Object is created using class name as data type.
Member functions can be defined inside or outside the class.
Scope resolution operator is used to define functions outside the class.

Constructor Function
A constructor is a special member function of a class which is used to initialize data members
of an object.

A constructor has the same name as the class and does not have any return type, not even
void.

A constructor is automatically called when an object of the class is created.


Why Constructor is Needed
Constructor is used to give initial values to data members.
It ensures that an object is in a valid state at the time of creation.
It reduces chances of garbage values.

Example of Constructor

class Student {
int roll;
public:
Student() {
roll = 1;
}
};

Here, the constructor initializes roll when the object is created.

Destructor Function
A destructor is a special member function of a class which is used to destroy objects and
release memory.

A destructor has the same name as the class, but is preceded by a tilde (~).

A destructor does not take arguments and does not return any value.

Example of Destructor

class Student {
public:
~Student() {
cout << "Object destroyed";
}
};

The destructor is automatically called when the object goes out of scope.

Difference Between Constructor and Destructor


Constructor initializes an object.
Destructor destroys an object.
Constructor is called when object is created.
Destructor is called when object is destroyed.

Initializing Member Values Without Constructor


Without constructor, data members are initialized using public data members or member
functions.

Example:

class Student {
public:
int roll;
};

int main() {
Student s1;
[Link] = 10;
}

This method is not safe because data can be modified directly.

Initializing Member Values Using Constructor


Using constructor, data members are initialized automatically.

Example:

class Student {
int roll;
public:
Student(int r) {
roll = r;
}
};

This method is safe and recommended.

Simple Program to Access and Manipulate Data Members

#include <iostream>
using namespace std;

class Student {
int marks;
public:
void setMarks(int m) {
marks = m;
}
void addMarks(int x) {
marks = marks + x;
}
void show() {
cout << "Marks = " << marks;
}
};

int main() {
Student s1;
[Link](50);
[Link](10);
[Link]();
return 0;
}

This program shows how data members are accessed and modified using member functions.

cin Function
cin is used to take input from the user.

It uses the extraction operator (>>).

Example:

int x;
cin >> x;

cout Function
cout is used to display output on the screen.

It uses the insertion operator (<<).

Example:

cout << x;

Example Using cin and cout

#include <iostream>
using namespace std;

class Student {
int roll;
public:
void input() {
cin >> roll;
}
void display() {
cout << "Roll = " << roll;
}
};

int main() {
Student s1;
[Link]();
[Link]();
return 0;
}

C vs C++ vs Java (Related to Constructor & I/O)


C does not support constructor and destructor.
C++ supports both constructor and destructor.
Java supports constructor but does not support destructor (uses garbage collection).

C uses printf() and scanf().


C++ uses cin and cout.
Java uses [Link]() and Scanner.

Exam Ready Lines (Must Write)


Constructor is used to initialize objects.
Destructor is used to destroy objects.
Constructor is automatically called.
Destructor has tilde (~) symbol.
cin is used for input and cout is used for output.

Dangers of Returning Reference to a Private Data Member


Returning reference to a private data member means direct access dena private data ko outside
world ke liye.

This breaks the concept of data hiding and data security.

Private data member ka reference return karne se:

 Data can be modified directly


 Control over data is lost
 Class becomes insecure
Example (Dangerous Case)

class Student {
private:
int marks;
public:
int& getMarks() {
return marks;
}
};

int main() {
Student s;
[Link]() = 100; // direct modification
}

Here, private data member marks is modified directly, which is unsafe.

Why It Is Dangerous
Private data is exposed indirectly.
Encapsulation is violated.
Data security is lost.

Exam line:
Returning reference to private data members breaks data hiding.

Constant Objects
A constant object is an object whose data cannot be modified after creation.

Constant object is declared using the keyword const.

Example of Constant Object

const Student s1;

Once created, s1 cannot modify its data members.

Constant Member Function


A constant member function is a function that cannot modify data members of the class.

It is declared using the keyword const at the end of function declaration.


Example of Constant Member Function

class Student {
int roll;
public:
int getRoll() const {
return roll;
}
};

Constant objects can call only constant member functions.

Importance of Constant Member Functions


Improves data safety.
Ensures object state is not changed.
Useful when working with constant objects.

Composition of Classes
Composition means one class contains an object of another class.

It represents a HAS-A relationship.

Example:
Car HAS-A Engine

Example of Composition

class Engine {
public:
void start() {
cout << "Engine started";
}
};

class Car {
Engine e;
public:
void drive() {
[Link]();
cout << "Car running";
}
};
Here, Car contains Engine → composition.

Difference Between Inheritance and Composition


Inheritance represents IS-A relationship.
Composition represents HAS-A relationship.

Composition provides better flexibility than inheritance.

Friend Function
A friend function is a non-member function that is allowed to access private and protected
members of a class.

Friend function is declared using the keyword friend.

Example of Friend Function

class Student {
private:
int roll;
public:
friend void show(Student s);
};

void show(Student s) {
cout << [Link];
}

Friend function breaks encapsulation intentionally.

Friend Class
A friend class is a class whose all member functions can access private members of another
class.

Example of Friend Class

class A {
private:
int x;
friend class B;
};

class B {
public:
void show(A a) {
cout << a.x;
}
};

Using Pointer in C++


A pointer is a variable that stores the address of another variable or object.

Pointers are used for:

 Dynamic memory allocation


 Object access
 Efficiency

Pointer to Object

Student *ptr;

Pointer can access object members using -> operator.

Example:

ptr->show();

Dynamic Creation of Objects Using new Operator


Objects created at runtime using new are called dynamic objects.

Example Using new

Student *s = new Student();

Memory is allocated in heap.

Destroying Objects Using delete Operator


Memory allocated using new must be released using delete.
Example Using delete

delete s;

This calls the destructor automatically.

Why delete Is Important


Prevents memory leakage.
Frees unused memory.
Improves program performance.

C vs C++ vs Java (Related Concepts)


C does not support classes and objects.
C++ supports pointers, new and delete operators.
Java does not use delete explicitly (uses garbage collection).

Friend function and friend class are available in C++ only, not in Java.

Exam Ready Lines (VERY IMPORTANT)


Returning reference to private data is dangerous.
Constant object cannot modify data.
Constant member function does not change object state.
Composition represents HAS-A relationship.
Friend function can access private members.
new creates object dynamically and delete destroys it.

Static Class Members


Static class members are those members which belong to the class itself, not to individual
objects.

Only one copy of static data member exists, which is shared by all objects of the class.

Static members are declared using the keyword static.

Static Data Members


Static data members store common data for all objects of a class.
They are declared inside the class but defined outside the class.

Example:

class Student {
public:
static int count;
};

int Student::count = 0;

Here, count is shared by all objects of Student.

Static Member Functions


Static member functions can access only static data members of the class.

They are called using class name, not object name.

Example:

class Student {
public:
static void showCount() {
cout << count;
}
};

Why Static Members Are Used


To store common information.
To maintain object count.
To save memory.

Container Classes
Container classes are classes that are used to store and manage a collection of objects.

They are part of the Standard Template Library (STL) in C++.

Container classes provide ready-made data structures.

Examples of Container Classes


vector → dynamic array
list → doubly linked list
deque → double ended queue
set → unique elements
map → key-value pairs

These containers can store primitive as well as user-defined objects.

Example of Container Class (vector)

#include <vector>
using namespace std;

vector<int> v;
v.push_back(10);
v.push_back(20);

Iterators
Iterators are objects used to point to elements inside a container.

They work like pointers and are used to traverse containers.

Iterators provide a common interface to access different container elements.

Example of Iterator

vector<int>::iterator it;
for(it = [Link](); it != [Link](); it++) {
cout << *it;
}

Here, it moves through the container v.

Why Iterators Are Needed


Containers store data differently.
Iterators provide uniform access.
They improve code flexibility.

Proxy Classes
A proxy class is a class that acts as a substitute or representative for another class.
It controls access to the original object.

Proxy class is mainly used for:

 Access control
 Security
 Lazy initialization

Simple Meaning of Proxy Class


Proxy means representative.
Proxy class does not do actual work, it delegates work to the real class.

Example of Proxy Class (Conceptual)

class RealObject {
public:
void work() {
cout << "Real work done";
}
};

class Proxy {
RealObject obj;
public:
void work() {
cout << "Access checked\n";
[Link]();
}
};

Here, Proxy controls access to RealObject.

Where Proxy Classes Are Used


Security systems
Database connections
Network communication

C vs C++ vs Java (Related Concepts)


Static members are available in C++ and Java, but not in C.
Container classes and iterators are part of C++ STL.
Java uses Collection Framework instead of STL.
Proxy concept exists in both C++ and Java, but implementation differs.

Exam Ready Lines (Must Write)


Static members belong to class, not object.
Only one copy of static data member exists.
Container classes store collection of objects.
Iterators are used to traverse containers.
Proxy class controls access to real object.
UNIT – 3(Operator overloading)
Operator Overloading – Fundamentals
Operator overloading is a feature of C++ that allows an operator to have more than one
meaning depending on the context.

In operator overloading, existing operators are given new behavior when they are used with
user-defined data types (objects).

Operator overloading makes programs more readable and natural.

Why Operator Overloading Is Needed


Operators like +, -, == work only on primitive data types.
Operator overloading allows these operators to work on objects.

It helps in writing clean and intuitive code.

Basic Syntax of Operator Overloading


Operator overloading is done using a special function called an operator function.

General form:

return_type operator symbol (arguments);

Simple Example of Operator Overloading

class Number {
int x;
public:
Number(int a) {
x = a;
}
Number operator + (Number obj) {
Number temp(0);
temp.x = x + obj.x;
return temp;
}
};

Here, + operator is overloaded to add two objects.


Important Points About Operator Overloading
Only existing operators can be overloaded.
Operator overloading does not change operator precedence.
At least one operand must be a user-defined object.

Restrictions of Operator Overloading


Some operators cannot be overloaded in C++.

Operators that cannot be overloaded include:

 . (dot operator)
 :: (scope resolution operator)
 ?: (conditional operator)
 sizeof

Operator overloading cannot create new operators.

The number of operands of an operator cannot be changed.

Operator Overloading and C vs C++ vs Java


C does not support operator overloading.
C++ supports operator overloading.
Java does not support operator overloading (except + for strings).

Operator Functions as Class Member Functions


When an operator function is defined inside a class, it is called a member operator function.

In this case, the left operand is the calling object.

Example: Operator Function as Class Member

class Number {
int x;
public:
Number(int a) {
x = a;
}
Number operator + (Number obj) {
Number temp(0);
temp.x = x + obj.x;
return temp;
}
};

Usage:

Number n1(10), n2(20);


Number n3 = n1 + n2;

Here, n1 is the calling object.

Advantages of Member Operator Functions


Direct access to private data members.
Simple syntax.
Better encapsulation.

Operator Functions as Friend Functions


When an operator function is defined outside the class and declared using friend, it is called a
friend operator function.

Friend operator functions can access private data members.

Example: Operator Function as Friend

class Number {
int x;
public:
Number(int a) {
x = a;
}
friend Number operator + (Number a, Number b);
};

Number operator + (Number a, Number b) {


Number temp(0);
temp.x = a.x + b.x;
return temp;
}

Why Friend Operator Functions Are Needed


When left operand is not an object.
When symmetry between operands is required.
Useful for binary operators like << and >>.
Difference Between Member and Friend Operator Functions
Member operator function requires object on left side.
Friend operator function allows non-object on left side.

Member function is part of class.


Friend function is not a member of class.

Member vs Friend Operator Overloading (Exam Table)

Member function:
Left operand must be an object.
Called using object.
Better encapsulation.

Friend function:
Left operand can be non-object.
Called like normal function.
More flexible.

Exam Ready Lines (Must Write)


Operator overloading gives new meaning to existing operators.
Only existing operators can be overloaded.
Dot and scope resolution operators cannot be overloaded.
Member operator function uses calling object.
Friend operator function provides flexibility.

Overloading Stream Functions (<< and >>)


Stream operators << and >> are used for output and input in C++.
These operators can be overloaded so that objects of a class can be used directly with cout and
cin.

Stream operator overloading improves readability and usability of programs.

Why Stream Operators Are Overloaded


By default, cout and cin work only with primitive data types.
Overloading allows them to work with user-defined objects.
Important Point (Exam)
Stream operators must be overloaded using friend functions, not as class member functions,
because the left operand (cout or cin) is not an object of the class.

Overloading << (Insertion Operator)


The insertion operator << is overloaded to display object data.

Example:

#include <iostream>
using namespace std;

class Student {
int roll;
public:
Student(int r) {
roll = r;
}
friend ostream& operator << (ostream &out, Student s);
};

ostream& operator << (ostream &out, Student s) {


out << "Roll = " << [Link];
return out;
}

Usage:

Student s1(10);
cout << s1;

Overloading >> (Extraction Operator)


The extraction operator >> is overloaded to take input into an object.

Example:

friend istream& operator >> (istream &in, Student &s);

Definition:

istream& operator >> (istream &in, Student &s) {


in >> [Link];
return in;
}

Usage:
cin >> s1;

Why ostream and istream Are Returned by Reference


Returning by reference allows operator chaining.

Example:

cout << a << b;

Unary Operator Overloading


Unary operators operate on a single operand.

Examples of unary operators:

 ++ (increment)
 -- (decrement)
 - (unary minus)

Unary operator overloading allows these operators to work on objects.

Example of Unary Operator Overloading

class Number {
int x;
public:
Number(int a) {
x = a;
}
void operator ++ () {
x = x + 1;
}
void show() {
cout << x;
}
};

Usage:

Number n1(5);
++n1;
[Link]();

Binary Operator Overloading


Binary operators operate on two operands.
Examples:

 +
 -
 *
 /

Binary operator overloading allows operations between two objects.

Example of Binary Operator Overloading

class Number {
int x;
public:
Number(int a) {
x = a;
}
Number operator + (Number obj) {
Number temp(0);
temp.x = x + obj.x;
return temp;
}
};

Usage:

Number n1(10), n2(20);


Number n3 = n1 + n2;

Difference Between Unary and Binary Operator Overloading


Unary operator works on one operand.
Binary operator works on two operands.

Unary operator function takes no argument (member function).


Binary operator function takes one argument (member function).

Type Conversion (Converting Between Types)


Type conversion means converting one data type into another.

In C++, type conversion can be done:

 From basic to class


 From class to basic
 From one class to another class
Basic Type to Class Type Conversion
This is done using a constructor.

Example:

class Number {
int x;
public:
Number(int a) {
x = a;
}
};

Usage:

Number n1 = 10;

Class Type to Basic Type Conversion


This is done using type conversion operator.

Example:

class Number {
int x;
public:
Number(int a) {
x = a;
}
operator int() {
return x;
}
};

Usage:

Number n1(10);
int a = n1;

Class Type to Class Type Conversion


This is done using a constructor of destination class.

Example:

class B;

class A {
int x;
public:
A(int a) {
x = a;
}
int get() {
return x;
}
};

class B {
int y;
public:
B(A a) {
y = [Link]();
}
};

Usage:

A obj1(10);
B obj2 = obj1;

C vs C++ vs Java (Related Topics)


C does not support operator overloading.
C++ supports operator overloading and type conversion.
Java does not support operator overloading (except +).

Stream operator overloading is a feature of C++ only.

Exam Ready Lines (Must Write)


Stream operators are overloaded using friend functions.
Unary operators work on single operand.
Binary operators work on two operands.
Type conversion is used to convert one type into another.
Constructor is used for basic to class conversion.
UNIT : 4 (Inheritance)
INHERITANCE
Inheritance is an object-oriented mechanism in which a new class acquires the properties and
behaviors of an existing class.
It helps in code reusability, easy maintenance, and modeling real-world relationships.

C language does not support inheritance.


C++ and Java support inheritance.

BASE CLASS AND DERIVED CLASS

Base Class
A base class (also called parent class) is the class whose members are inherited by another class.

Derived Class
A derived class (also called child class) is the class that inherits data members and member
functions from the base class and can also define its own members.

Example (conceptual):
Vehicle → Base class
Car → Derived class

C++ allows multiple inheritance.


Java allows multiple inheritance only through interfaces.

PROTECTED MEMBERS
Protected members are accessible:

 Inside the same class


 Inside derived (child) classes

They are not accessible outside the class hierarchy.

Protected access is mainly used in inheritance to give limited access to derived classes.

C → no protected members
C++ → protected keyword supported
Java → protected members accessible in subclass and same package
RELATIONSHIP BETWEEN BASE CLASS AND DERIVED CLASS
The relationship between base and derived class is called IS-A relationship.

Example:
Car IS-A Vehicle
Student IS-A Person

IS-A relationship is a very important exam keyword.

CONSTRUCTORS IN DERIVED CLASSES


When an object of a derived class is created:

 First, the base class constructor is called


 Then, the derived class constructor is called

This ensures that the base part of the object is initialized first.

In Java, the base class constructor is called using the super() keyword.

DESTRUCTORS IN DERIVED CLASSES


When a derived class object is destroyed:

 First, the derived class destructor is executed


 Then, the base class destructor is executed

The destruction order is the reverse of construction order.

Java does not have destructors.


Memory is managed by the garbage collector.

PUBLIC INHERITANCE
In public inheritance:

 Public members of base class remain public


 Protected members remain protected

The IS-A relationship is preserved.


This is the most commonly used inheritance type.
Java inheritance behaves like public inheritance only.

PRIVATE INHERITANCE
In private inheritance:

 Public members of base class become private


 Protected members become private

The IS-A relationship is not preserved.


This type is rarely used.

Java does not support private inheritance.

PROTECTED INHERITANCE
In protected inheritance:

 Public members become protected


 Protected members remain protected

Access is restricted but still available to subclasses.

This is a C++-specific feature.

RELATIONSHIP AMONG OBJECTS IN AN INHERITANCE HIERARCHY


In an inheritance hierarchy:

 A derived class object contains both base class and derived class parts
 A base class pointer can point to a derived class object

This relationship enables polymorphism.

Java uses references instead of pointers, but the concept is the same.

ABSTRACT CLASSES
An abstract class is a class that:

 Contains at least one pure virtual function


 Cannot be used to create objects
It is used to force derived classes to implement specific functions.

In Java, abstract classes are declared using the abstract keyword.


Interfaces provide a similar concept.

VIRTUAL FUNCTIONS
A virtual function is a member function whose call is resolved at runtime, not at compile time.

When a base class pointer points to a derived class object, the derived class function is called.

This enables runtime polymorphism.

C → no virtual functions
C++ → uses virtual keyword
Java → methods are virtual by default (except static and final)

DYNAMIC BINDING
Dynamic binding means the function call is linked at runtime.

Dynamic binding occurs only when:

 Inheritance is used
 Base class pointer refers to derived class object
 Function is declared virtual

Static binding occurs with non-virtual functions.

VIRTUAL DESTRUCTORS
If a base class pointer is used to delete a derived class object and the destructor is not virtual:

 Derived class destructor will not be called


 This causes memory leakage

Therefore, in inheritance, the base class destructor should always be virtual.

Java does not have destructors, so this issue does not exist.
UNIT – 5(Advanced Topics)
MULTIPLE INHERITANCE

Definition:
Multiple inheritance is when a derived class inherits from more than one base class.
It allows a class to combine properties and methods from multiple sources.

Purpose:

 Reuse code from multiple base classes


 Combine functionalities of multiple classes
 Model real-world relationships where an object “IS-A” of multiple types

Syntax in C++:

class Base1 { /* members */ };


class Base2 { /* members */ };
class Derived : public Base1, public Base2 { /* members */ };

Example:

#include <iostream>
using namespace std;

class A {
public:
void showA() { cout << "A class\n"; }
};

class B {
public:
void showB() { cout << "B class\n"; }
};

class C : public A, public B { };

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

Important Points:

 If both base classes have members with same name → ambiguity occurs
 Solve ambiguity using scope resolution operator
 Leads to diamond problem if base classes share a common ancestor
C vs C++ vs Java:

 C → does not support multiple inheritance


 C++ → allows multiple inheritance with : syntax
 Java → does not allow direct multiple inheritance, uses interfaces instead

VIRTUAL BASE CLASSES

Definition:
Virtual base class is used to prevent multiple copies of a common base class in multiple
inheritance.
Solves the diamond problem.

Diamond Problem:

A
/ \
B C
\ /
D

Without virtual inheritance, D would have two copies of A, leading to redundancy and
ambiguity.

Syntax:

class A { public: int x; };


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

Example:

D obj;
obj.x = 10; // only one A part exists

Important Points:

 Use virtual keyword in intermediate base classes


 Only C++ supports virtual base classes, Java solves diamond problem via interfaces

POINTERS TO CLASSES AND CLASS MEMBERS


Definition:
Pointers can store address of objects or class members.

Purpose:

 Dynamic object access


 Enable runtime polymorphism
 Efficient memory use

Pointer to Object Syntax:

ClassName *ptr = &object;


ptr->memberFunction();

Pointer to Member Function Syntax:

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


void (A::*fptr)() = &A::show;
(Aobj.*fptr)();

Example:

#include <iostream>
using namespace std;

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

int main() {
A obj;
A *ptr = &obj;
ptr->display();
}

C vs C++ vs Java:

 C → pointers only for primitive variables


 C++ → object and function pointers allowed
 Java → no pointers, references used instead

MULTIPLE CLASS MEMBERS

Definition:
A class can contain multiple types of members:
 Data members
 Member functions
 Static members
 Constant members
 Objects of other classes
 Pointers, arrays

Example:

class Student {
int roll; // data member
static int count; // static member
const int maxMarks; // constant member
public:
Student(int r, int m) : maxMarks(m) { roll = r; }
void display() { cout << roll << " " << maxMarks; }
};

Purpose:

 Encapsulate related data and behavior


 Organize complex information
 Reuse objects inside other classes

TEMPLATES

Definition:
Templates allow writing generic classes and functions that can work with any data type.

Purpose:

 Code reuse
 Avoid writing same function for multiple types
 Write generic data structures

Function Template Example:

template <typename T>


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

int main() {
cout << add(10, 20); // int
cout << add(3.5, 2.5); // double
}

Class Template Example:


template <class T>
class Box {
T value;
public:
Box(T v) { value = v; }
T get() { return value; }
};

int main() {
Box<int> b1(10);
cout << [Link]();
}

C vs C++ vs Java:

 C → no templates
 C++ → templates available
 Java → uses generics instead

EXCEPTION HANDLING

Definition:
Exception handling is a mechanism to handle runtime errors gracefully using try, catch,
throw.

Purpose:

 Avoid program crash


 Provide meaningful messages
 Handle unexpected conditions

Syntax Example:

#include <iostream>
using namespace std;

int main() {
int x = 10, y = 0;
try {
if (y == 0) throw "Division by zero error!";
cout << x / y;
}
catch (const char* msg) {
cout << msg;
}
}

Important Points:
 Multiple catch blocks can handle different exception types
 throw can throw objects, literals, or pointers
 Resource cleanup can be done using destructors

C vs C++ vs Java:

 C → no built-in exception handling


 C++ → supports try-catch-throw
 Java → supports try-catch-finally

FILE HANDLING

Definition:
File handling allows programs to read and write data from/to files.

Purpose:

 Store persistent data


 Save reports, logs
 Data sharing between programs

Classes (C++):

 ofstream → write
 ifstream → read
 fstream → read/write

Example:

#include <fstream>
#include <iostream>
using namespace std;

int main() {
ofstream fout("[Link]");
fout << "Hello World" << endl;
[Link]();

ifstream fin("[Link]");
string line;
while (getline(fin, line)) {
cout << line << endl;
}
[Link]();
}

C vs C++ vs Java:
 C → FILE*
 C++ → fstream classes
 Java → FileReader / FileWriter / BufferedReader

You might also like