0% found this document useful (0 votes)
5 views

c++_notes[1]

Object-Oriented Programming (OOP) is a programming paradigm that uses objects to represent real-world entities and aims to encapsulate data and functions. Key concepts of OOP include classes, objects, inheritance, polymorphism, encapsulation, and abstraction, which promote code reusability, modularity, and data security. OOP is widely applied in various domains such as game development, web development, and enterprise software, enhancing maintainability and flexibility in software design.

Uploaded by

suganya.cse
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

c++_notes[1]

Object-Oriented Programming (OOP) is a programming paradigm that uses objects to represent real-world entities and aims to encapsulate data and functions. Key concepts of OOP include classes, objects, inheritance, polymorphism, encapsulation, and abstraction, which promote code reusability, modularity, and data security. OOP is widely applied in various domains such as game development, web development, and enterprise software, enhancing maintainability and flexibility in software design.

Uploaded by

suganya.cse
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Basic Concepts of Objects Oriented Programming:

Object-Oriented Programming or OOPs refers to languages that use objects in programming. Object-oriented
programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The
main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code
can access this data except that function.

OOPs Concepts:
 Class
 Objects
 Data Abstraction
 Encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding
 Message Passing
1.CLASS:
A class is a user-defined data type. It consists of data members and member functions, which can be accessed
and used by creating an instance of that class. It represents the set of properties or methods that are common to all
objects of one type. A class is like a blueprint for an object.
Syntax:
class ClassName
{
private:
Variable declaration; Function declaration;
public:
Variable declaration; Function declaration;
};
Example:
class ThisClass {
public:
int var; // data member
void print() { // member method
cout << "Hello";
}
};

Components of a Class
1. Data Members (Attributes):
o Variables declared inside a class that store the state or properties of an object.

o Example: int age, string name.

2. Member Functions (Methods):


o Functions declared inside a class that define the behavior or actions of an object.

o Example: void displayInfo().

3. Access Specifiers:
o Control the visibility and accessibility of class members.

o Public: Accessible from outside the class.

o Private: Accessible only within the class.

o Protected: Accessible within the class and derived classes.

2.OBJECT:
An object is an instance of a class. A class acts as a blueprint that defines the structure and behavior (data members and
member functions), and the object is a concrete realization of that blueprint.
Syntax:
To create an object of the class, use the syntax:
ClassName objectName;
Characteristics of an Object
1. Instance of a Class:
o A class defines the properties (attributes) and behaviors (methods), while an object is the actual
representation of those properties and behaviors.
o Multiple objects can be created from the same class, and each object can have different states.

2. Memory Representation:
o When an object is created, it occupies space in memory for its data members (attributes).

3. Unique Identity:
o Each object has its own identity and stores its own state (values of attributes).

4. Access Using the Dot Operator:


o Objects interact with the class's methods and attributes using the dot operator (.).
Attributes of an Object
Each object has two main components:
1. State:
o Represented by the values of its data members (attributes).

o Example: name and age in the Person class above.

2. Behavior:
o Represented by the member functions (methods) of the class.

o Example: displayInfo() in the Person class.

3.Abstraction:
It is the process of hiding unnecessary details and showing only the essential features of an object. In C++, abstraction
is implemented using classes, access modifiers, and in advanced cases, abstract classes or interfaces.
Types of Abstraction:
1. Data abstraction – This type only shows the required information about the data and ignores unnecessary
details.
2. Control Abstraction – This type only shows the required information about the implementation and ignores
unnecessary details.

Abstraction in C++
In C++, abstraction is achieved using:
Abstraction using Classes
We can implement Abstraction in C++ using classes. The class helps us to group data members and member functions
using available access specifiers. A Class can decide which data member will be visible to the outside world and which
is not.
Abstraction in Header files
One more type of abstraction in C++ can be header files. For example, consider the pow() method present in math.h
header file. Whenever we need to calculate the power of a number, we simply call the function pow() present in the
math.h header file and pass the numbers as arguments without knowing the underlying algorithm according to which
the function is actually calculating the power of numbers.
Abstraction using Access Specifiers
Access specifiers are the main pillar of implementing abstraction in C++. We can use access specifiers to enforce
restrictions on class members. For example:
 Members declared as public in a class can be accessed from anywhere in the program.
 Members declared as private in a class, can be accessed only from within the class. They are not allowed to be
accessed from any part of the code outside the class.
Encapsulation:
Encapsulation in C++ is defined as the wrapping up of data and information in a single unit. In Object Oriented
Programming, Encapsulation is defined as binding together the data and the functions that manipulate them.

Two Important property of Encapsulation :


1. Data Protection: Encapsulation protects the internal state of an object by keeping its data members private.
Access to and modification of these data members is restricted to the class’s public methods, ensuring
controlled and secure data manipulation.
2. Information Hiding: Encapsulation hides the internal implementation details of a class from external code.
Only the public interface of the class is accessible, providing abstraction and simplifying the usage of the class
while allowing the internal implementation to be modified without impacting external code.
Features of Encapsulation :
 Functions in a class can only be accessed via objects, not directly.
 A function is part of encapsulation only if it uses the class's member variables.
 Without functions using member variables, encapsulation isn't achieved.
 Encapsulation enhances readability, maintainability, and security by bundling data and methods.
 It controls and restricts the modification of data members.

Inheritance:
Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows one class (the child or derived
class) to inherit the properties and behaviors of another class (the parent or base class). This promotes code reuse and
establishes a hierarchy between classes.
Syntax of Inheritance in C++
class derived_class_name : access-specifier base_class_name
{
// body ....
};
where,
 class: keyword to create a new class
 derived_class_name: name of the new class, which will inherit the base class
 access-specifier: Specifies the access mode which can be either of private, public or protected. If neither is
specified, private is taken as default.
 base-class-name: name of the base class.
Access Specifiers in Inheritance:
 Public: Public and protected members of the base class remain public/protected in the derived class.
 Protected: Public and protected members of the base class become protected in the derived class.
 Private: Public and protected members of the base class become private in the derived class.
Types of Inheritance
1.Single Inheritance:
o A class inherits from a single base class.

Syntax:
class A { /* Base class */ };
class B : public A { /* Derived class */ };
2.Multilevel Inheritance:
 A class inherits from a derived class.
Syntax:
class A { /* Base class */ };
class B : public A { /* Derived from A */ };
class C : public B { /* Derived from B */ };

3.Multiple Inheritance:
 A class inherits from multiple base classes.
class A { /* Base class 1 */ };
class B { /* Base class 2 */ };
class C : public A, public B { /* Derived from A and B */ };
4.Hierarchical Inheritance:
 Multiple derived classes inherit from a single base class.
cpp
CopyEdit
class A { /* Base class */ };
class B : public A { /* Derived from A */ };
class C : public A { /* Derived from A */ };
Hybrid Inheritance:
 A combination of multiple and multilevel inheritance.
Features of Inheritance:
1. Code Reusability:
o A derived class can reuse the functionality of the base class, reducing duplication.

2. Extensibility:
o Derived classes can extend or override the behavior of the base class.

3. Hierarchy:
o Models relationships between objects, such as "is-a" (e.g., a Car is-a Vehicle).

Polymorphism:
The word “polymorphism” means having many forms. In simple words, we can define polymorphism as the ability of a
message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time
can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person
exhibits different behavior in different situations. This is called polymorphism. Polymorphism is considered one of the
important features of Object-Oriented Programming.
Types of Polymorphism
 Compile-time Polymorphism
 Runtime Polymorphism
1. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator overloading.
A.Function Overloading
Definition: Function overloading allows multiple functions with the same name but different parameters
(number or type) in the same scope.
Key Concept:
Overloaded functions perform different tasks based on the arguments passed.
How It Works:
Number of Arguments: Functions can have different numbers of arguments.
Type of Arguments: Functions can differ in the type of their arguments.
Rules for Function Overloading:
The functions must differ in the number or type of parameters.
Overloading cannot be done by changing only the return type of functions.
Default arguments should not create ambiguity between overloaded functions.
B. Operator Overloading
1. Definition:
o Operator overloading allows giving operators a custom meaning for user-defined data types.

o It enables operators like +, -, *, etc., to perform specific tasks based on the context of the operands.

2. Key Concept:
o The same operator behaves differently depending on the types of operands.

o Example: The + operator adds integers and concatenates strings.


3. Syntax of Operator Overloading:
o Use the operator keyword to define an overloaded operator.

o Must be a member function or a friend function.

o Example: Overloading +:

class MyClass {
public:
MyClass operator+(const MyClass& obj) {
// Define the behavior for +
}
};
4. Rules for Operator Overloading:
o Only existing operators can be overloaded; new operators cannot be created.

o Operators like ::, sizeof, .*, and . cannot be overloaded.

o Overloaded operators must have at least one user-defined type as an operand.

o Precedence and associativity of operators remain unchanged.

2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and dynamic polymorphism are other
names for runtime polymorphism. The function call is resolved at runtime in runtime polymorphism. In contrast, with
compile time polymorphism, the compiler determines which function call to bind to the object after deducing it at
runtime.
A. Function Overriding
Function Overriding occurs when a derived class has a definition for one of the member functions of the base class.
That base function is said to be overridden.
B.Virtual Function
A virtual function is a member function that is declared in the base class using the keyword virtual and is re-defined
(Overridden) in the derived class.
Some Key Points About Virtual Functions:
 Virtual functions are Dynamic in nature.
 They are defined by inserting the keyword “virtual” inside a base class and are always declared with a base
class and overridden in a child class
 A virtual function is called during Runtime
Dynamic Binding:
Dynamic binding in C++ is a practice of connecting the function calls with the function definitions by avoiding the
issues with static binding, which occurred at build time. Because dynamic binding is flexible, it avoids the drawbacks
of static binding, which connected the function call and definition at build time.
In simple terms, Dynamic binding is the connection between the function declaration and the function call.

Use of dynamic binding

On that note, dynamic binding also helps us to handle different objects using a single function name. It also reduces the
complexity and helps the developer to debug the code and errors.
How to Implement Dynamic Binding?
Dynamic binding in C++ can be implemented using virtual functions and polymorphism. Using virtual functions, we
can declare a base class (parent class or superclass), and the derived classes can be used to override them. Virtual
functions in C++ are declared within the base class and are overridden by the derived classes.
Characteristics of Dynamic Binding in C++
The process when the connection is formed between the function calls with its definition and any static binding issue
that occurs during the build time is avoided is known as data binding. Below are some of the characteristics of Dynamic
Binding.
 Dynamic binding occurs at runtime.

 Its execution is slower as compared to the static binding.

 We can achieve dynamic binding through virtual functions. We cannot declare a virtual function as static. The
virtual functions are declared within the base class.

 Through Dynamic binding, we can achieve run-time polymorphism.

 Pointers and references are used in implementing dynamic binding in C++.

Message Passing:
Message passing in C++ refers to the process of passing a message, or data, between different objects or components in
a program. This can be done in many ways, such as function calls, events, or inter-process communication. The specific
implementation of message passing will depend on the program's design and the system's needs.
How does this work?
The following steps to implement message passing in c++.
 Creating a class and its associated Object.
 A message can be used to assist objects in communicating with one another.

 An object that will invoke the function in another object receives a message.

 Thus, a message is used to start a conversation between two things.


Benefits of OOP
 Code Reusability:
 Inheritance allows the reuse of existing code by creating new classes based on existing ones, reducing
redundancy.
 Modularity:
 Code is divided into objects, making it easier to modify, debug, and maintain individual parts of the system.
 Data Security:
 Encapsulation hides the internal details of objects and restricts access, ensuring that sensitive data is protected
from unauthorized access.
 Improved Productivity:
 Reusable components and modular design increase development speed and reduce effort.
 Real-World Modeling:
 OOP maps real-world entities into programming objects, making software design more intuitive and natural.
 Flexibility and Scalability:
 Polymorphism allows functions and operators to behave differently based on context, making the system
adaptable to change.
 New features can be added with minimal changes to existing code.
 Maintainability:
 OOP promotes well-structured and organized code, making it easier to maintain and update in the long run.
 Code Readability:
 Objects and classes provide a clear structure, improving the understanding and readability of code.
 Abstraction:
 Hides complexity by exposing only the essential features of an object, simplifying the design and
implementation process.
 Support for Real-Time Problems:
 OOP principles are well-suited for solving real-world problems in applications like simulations, games, and
GUIs.
Applications of OOP:
1. Real-World Modeling and Simulation:
o Description: OOP is ideal for creating simulations that model real-world scenarios with objects and
their interactions.
o Examples:

 Weather simulations.
 Traffic simulations.
 Business process modeling.
2. Graphical User Interfaces (GUIs):
o Description: OOP is commonly used to develop GUI-based applications where components like
buttons, sliders, and text fields can be represented as objects.
o Examples:

 Desktop applications (e.g., Microsoft Word, Photoshop).


 GUI frameworks like Java Swing, Tkinter (Python), and Qt.
3. Game Development:
o Description: OOP simplifies game development by representing characters, weapons, vehicles, and
environments as objects.
o Examples:

 Unity (C#) and Unreal Engine (C++) use OOP concepts.


 Games like Fortnite, PUBG, and Minecraft.
4. Web Development:
o Description: OOP is heavily used in backend development for creating modular, maintainable, and
scalable web applications.
o Examples:

 Frameworks like Django (Python), Laravel (PHP), and Spring (Java).


 Content management systems like WordPress.
5. Mobile App Development:
o Description: OOP helps in structuring mobile apps by organizing components into objects.

o Examples:

 Android apps using Java or Kotlin.

 iOS apps using Swift or Objective-C.


6. Enterprise Software Development:
o Description: Large-scale enterprise applications leverage OOP for better modularity and scalability.

o Examples:

 Enterprise Resource Planning (ERP) systems like SAP.


 Customer Relationship Management (CRM) systems like Salesforce.
7. Database Management Systems (DBMS):
o Description: OOP principles are used in creating object-oriented databases that store data as objects
rather than relational tables.
o Examples:

 Object-oriented DBMS like ObjectDB and db4o.


 Hibernate (an ORM tool for Java).

8. Scientific and Engineering Applications:


o Description: Complex computations and simulations in science and engineering are implemented
using OOP.
o Examples:

 MATLAB object-oriented features for numerical analysis.


 CAD software for designing mechanical parts.

9. Artificial Intelligence and Machine Learning:


o Description: OOP helps in designing reusable components for AI/ML pipelines.

o Examples:

 Libraries like TensorFlow, PyTorch, and Scikit-learn use OOP concepts.

 Building neural networks and models.

10. Operating Systems and System Programming:


o Description: OOP is used in developing parts of operating systems for better modularity.

o Examples:

 Linux kernel (C++).


 Windows (built using C++).
Classes &Objects:

A class is a way to bind the data and its associated functions together i.e.) It encapsulate data and functions together
into a single Unit.

A class specification has 2 Parts.

1. Class declaration

2. Class function definition.

Syntax:

Class Class name

Private:

Variable declaration; Function declaration;

Public: Variable declaration; Function declaration;

};
Where, Class-is a Keyword

Class is a user defined name Body of the class enclosed with braces and terminated with semicolon.

The class body contains the declaration of variables, functions, these variables are collectively called
members and the function are called member function

The keyword private and public are known as visibility labels and it should end with color.

By default all the members are private.

Creating objects:

Objects are instance of class. Our a class hasbeen declared ne can create Object of the clans by using
the class home.

Accessing class members:

Class members can be accessed by using the objects ofthose clans

Syntax:

Object name. Function name actual arguments;

Defining member function:

Member functions can define in two places.

1. inside class definition.

2. outside class definition.

Outside definition:

Member functions that are declared inside of the clans con be defined separately outside of
the class.

Data Members :

Definition: Data members are variables defined within a class. They represent the properties or
attributes of a class, and their values are specific to each object of the class.

1. Declaration and Scope:

o Data members are declared inside a class.

o Their scope is limited to the class in which they are defined.


2. Access Specifiers:

o Data members can be declared as private, protected, or public.

o Default access specifier in C++ is private.

3. Types of Data Members:

o Instance Data Members: Specific to an object of the class.

o Static Data Members: Shared among all objects of the class. Declared using the

4. Initialization:

o Non-static data members are initialized through constructors.

o Static data members are initialized outside the class.

int Counter::count = 0; // Static data member initialization

5. Encapsulation:

o Data members are usually kept private to protect them from unintended
modifications.

o Public member functions (getters and setters) are used to access and modify private
data members.

6. Memory Allocation:

o Non-static data members have memory allocated for each object.

o Static data members are allocated once for the entire class.

Advantages of Data Members:

1. Encapsulation ensures data security.

2. Helps in defining object properties.

3. Supports object-oriented design principles.

Member Functions

Definition: Member functions are functions defined inside a class. They define the behavior or
operations that can be performed on the data members of the class. They operate on the data
members and provide functionality to the objects of the class.

1. Declaration and Syntax:

A member function is declared inside a class and can be defined either:

 Inside the class (inline).


 Outside the class (using the scope resolution operator ::).

2. Access Specifiers:
Member functions can be declared as public, protected, or private, which defines their access
level:

 Public: Accessible from outside the class.


 Private: Accessible only within the class.
 Protected: Accessible within the class and derived classes.

3. Types of Member Functions:

1. Constructor: A special member function automatically called when an object is created. It is


used to initialize data members.

Destructor: A special member function automatically called when an object is destroyed. It


cleans up resources.

2. Accessors (Getters): Functions that retrieve the value of private data members without
modifying them.
3. Mutators (Setters): Functions that modify private data members.
4. Inline Member Functions: Defined inside the class. The compiler attempts to expand their
code directly where they are called, avoiding function call overhead.
5. Static Member Functions: Can be called without creating an object. These functions can
access only static data members of the class.
6. Friend Functions: A friend function is not a member of the class but can access its private
and protected members.

4. Inline vs Non-Inline Member Functions:

Feature Inline Non-Inline


Definition Inside the class Outside the class
Execution Speed Faster due to inline expansion Normal function call overhead applies
Usage For small functions For complex functions

5. Encapsulation with Member Functions:

Member functions ensure encapsulation by providing controlled access to the private data
members using getters and setters.

Advantages of Member Functions:

1. Encapsulate operations on data members.


2. Promote modularity and code reusability.
3. Enable controlled access to private/protected members.
4. Can be overloaded to support polymorphism.
The this Pointer

Definition:

The this pointer is an implicit pointer available in all non-static member functions of a class. It points
to the current object of the class that invoked the member function.

Key Characteristics of the this Pointer:

1. Implicit Pointer:
o It is automatically passed to all non-static member functions of the class.
o You don't need to explicitly declare or pass it.
2. Current Object:
o The this pointer holds the address of the current object, allowing member functions
to refer to the invoking object.
3. Scope:
o It is available only in non-static member functions. Static member functions do not
have access to the this pointer since they are not tied to any specific object.
4. Read-Only Pointer:
o The address stored in the this pointer cannot be modified, ensuring that it always
points to the correct invoking object.

Usage of the THIS Pointer:

1. Accessing Members of the Current Object: The this pointer allows member functions to
refer explicitly to the data members of the invoking object.
2. Resolving Name Conflicts: When local variables shadow class data members, the this
pointer helps to resolve ambiguity.
3. Returning the Current Object: The this pointer can be used to return the current object from
a member function, enabling method chaining.

Usage of Method Chaining:

4. Used in Operator Overloading: The this pointer is often used in operator overloading to
refer to the invoking object.

Limitations of the this Pointer:

1. Unavailable in Static Member Functions: Static member functions do not have access to the
this pointer as they are not associated with any specific object.
2. Cannot Be Modified: The this pointer is a constant pointer and cannot be reassigned to
point to another object.

Advantages of the this Pointer:

1. Resolves ambiguity when parameter names conflict with class data members.
2. Enables method chaining by returning the current object.
3. Helps in accessing the invoking object in operator overloading and other member functions.
Constructors

Definition:

A constructor is a special member function that is automatically called when an object of a class is
created. It initializes the data members of the class.

Key Features of Constructors:

1. Same Name as the Class: The name of the constructor must be the same as the class name.
2. No Return Type: Constructors do not have a return type, not even void.
3. Automatic Invocation: A constructor is automatically called when an object is created.
4. Overloading: Constructors can be overloaded to allow multiple ways of object initialization.
5. Types of Constructors:
o Default Constructor: A constructor with no parameters or with default arguments.
o Parameterized Constructor: A constructor that takes arguments to initialize the data
members.
o Copy Constructor: A constructor that initializes an object by copying data from
another object of the same class.
6. Constructor Initialization List: Used to initialize data members directly.

Destructors

Definition:

A destructor is a special member function that is automatically called when an object goes out of
scope or is deleted. It is used to clean up resources allocated during the lifetime of the object.

Key Features of Destructors:

1. Same Name as the Class with a ~: The destructor's name is preceded by a tilde (~).
2. No Parameters or Return Type: Destructors cannot have parameters or return any value.
3. Automatic Invocation: A destructor is automatically called when:
o The object goes out of scope.
o The delete operator is used on an object.
4. No Overloading: A class can have only one destructor, and it cannot be overloaded.
5. Used for Resource Management: Destructors are used to free dynamically allocated
memory, close files, release locks, etc.

Differences Between Constructors and Destructors:

Feature Constructor Destructor


Purpose Initializes an object. Cleans up and releases resources.
Name Same as the class name. Same as the class name, preceded by a ~.
Called when an object goes out of scope or is
Invocation Called when an object is created.
deleted.
Overloading Can be overloaded. Cannot be overloaded.
Parameters Can accept parameters. Cannot have parameters.
Use of Constructor and Destructor Together:

Constructors and destructors are often used together in programs that involve dynamic memory
allocation, file handling, or resource management.

FRIEND FUNCTION:

Defenition:

A friend function in C++ is a function that is not a member of a class but is granted access to the
private and protected members of that class. It is declared within the class by using the friend
keyword and defined outside the class.

Key characteristics of friend function:

 Access Control: Can access private and protected members of the class.
 Declaration: Declared inside the class but defined like a normal function outside it.
 Not a Member: Does not belong to the class's scope and is called like a regular function.
 Purpose: Commonly used for operator overloading or when external functions need access
to a class's internals.

Syntax of Friend Function:

class ClassName {

private:

// Private members

int privateVar;

public:

// Friend function declaration

friend void FriendFunctionName(const ClassName &obj);

};

1.Declaration Inside the Class

 The friend function is declared inside the class using the friend keyword.
 This declaration tells the compiler that the function will have access to the private and
protected members of the class.
 The function is declared without specifying its definition in the class body.
2.Definition Outside the Class

 The actual logic of the friend function is defined outside the class body, just like a normal
function.
 The definition uses the same function name and parameter list as the declaration.
 Inside the function, private and protected members of the class can be accessed

3.Usage in Code

 The friend function can be called directly in the main program or any other function.
 It is not called using an object of the class, as it is not a member of the class.

NOTE:

1. The friend keyword is used only in the class declaration, not in the function definition.
2. Friend functions can be regular functions or operator overloads.
3. Overuse of friend functions can violate encapsulation, so use them judiciously.

Example:

#include <iostream>

using namespace std;

class MyClass {

private:

int data;

public:

MyClass(int val) : data(val) {}

// Friend function declaration

friend void displayData(const MyClass &obj);

};

// Friend function definition


void displayData(const MyClass &obj) {

cout << "Private Data: " << obj.data << endl;

int main() {

MyClass obj(42);

displayData(obj); // Call the friend function

return 0;

Advantages:

1. Access Control: Can access private/protected members of a class.


2. Operator Overloading: Useful for overloading binary operators.
3. Flexibility: Enables external functionality without making data public.
4. Multi-Class Access: One friend function can work with multiple classes.
5. Encapsulation over Globals: Better than global functions for specific access.

Disadvantage:

1. Breaks Encapsulation: Violates data hiding principles.


2. Tight Coupling: Creates dependency between class and function.
3. Maintenance Challenges: Harder to debug and manage.
4. No Inheritance: Friendship is not inherited in derived classes.
5. Less OOP: Functions outside class scope reduce object-oriented purity.

Static Variables and Functions:

Static Variables:

A static variable in a class is shared across all objects of that class. It belongs to the class rather
than any specific instance.

Characteristics :

 Shared Across All Instances: A single copy of the static variable is shared among all objects
of the class.
 Class-Level Storage: The variable is stored in a special memory area and persists throughout
the program's lifetime.
 Initialized Once: Static variables are initialized only once, and their value is retained across
function calls.
 Defined Outside the Class: They must be defined outside the class if declared inside it.
Syntax:

class ClassName {

static int staticVar; // Declaration

};

int ClassName::staticVar = 0; // Definition and initialization

Static Functions:

Static functions are class methods that do not operate on a specific instance of the class. They
can only access static variables or other static functions.

Characteristics :

 No this Pointer: They do not receive a this pointer, as they are not tied to any specific
object.
 Only Access Static Members: They can only work with static variables or call other static
functions.
 Class-Level Access: Static functions are called using the class name rather than an object.

Syntax:

class ClassName {

public:

static void staticFunction() {

// Logic

};

Advantages:

1. Shared Data: Useful for maintaining shared data among all objects (e.g., counters).
2. Global Access via Class: Static members can be accessed without creating an object of the
class.
3. Encapsulation: Provides a way to encapsulate global data/functions within a class scope.
Disadvantage:

1. Limited Scope: Static functions cannot access non-static members of the class.
2. Global-like Behavior: Overusing static members can lead to global-like behavior, which may
reduce modularity.
3. Requires Extra Definition: Static variables require a separate definition outside the class.

Operator Overloading:

Definition:

Operator Overloading is a feature in C++ that allows developers to redefine the behavior of
operators for user-defined types (e.g., classes or structs). This enables operators like +, -, *, or ==
to work with objects in a meaningful way, similar to built-in data types.

Key features:

 Custom Operator Behavior: Redefines how operators work with user-defined types (e.g.,
classes).
 Syntax: Done using the operator keyword followed by the operator symbol.
 Member and Non-Member Functions: Can be overloaded as member functions (with the
left operand as the class object) or non-member functions (friend functions).
 Intuitive Code: Makes code more intuitive by allowing natural use of operators with objects.
 Limitations: Cannot overload certain operators (e.g., ::, ., sizeof) or change operator
precedence.

Syntax:

Member Function:

class ClassName {

public:

ReturnType operatorSymbol(Arguments) {

// Logic for operator

};

Non-Member (Friend) Function:

class ClassName {

friend ReturnType operatorSymbol(const ClassName &lhs, const ClassName &rhs);


};

Types of Operators That Can Be Overloaded:

 Arithmetic Operators: +, -, *, /, %
 Relational Operators: ==, !=, <, >, <=, >=
 Logical Operators: &&, ||, !
 Bitwise Operators: &, |, ^, ~, <<, >>
 Assignment Operators: =, +=, -=, *=, /=
 Unary Operators: ++, --, -, +
 Other Operators: [], (), ->, new, delete.

Advantages:

1. improves Readability: Makes code easier to understand by allowing intuitive use of


operators with objects.
2. Custom Behavior: Allows operators to work with user-defined types in a meaningful way.
3. Reusability: Enhances the flexibility and reusability of code.

Disadvantages:

 Complexity: Overloading can make code harder to understand if not used judiciously.
 Debugging Difficulty: Errors in overloaded operators can be harder to identify.
 Risk of Misuse: Overloading operators in a non-intuitive way can confuse users of the class.

You might also like