c++_notes[1]
c++_notes[1]
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.
3. Access Specifiers:
o Control the visibility and accessibility of class members.
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).
2. Behavior:
o Represented by the member functions (methods) of the 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.
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: 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.
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.
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.
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.
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.
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:
o Examples:
o Examples:
o Examples:
o Examples:
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.
1. Class declaration
Syntax:
Private:
};
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.
Creating objects:
Objects are instance of class. Our a class hasbeen declared ne can create Object of the clans by using
the class home.
Syntax:
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.
o Static Data Members: Shared among all objects of the class. Declared using the
4. 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 Static data members are allocated once for the entire class.
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.
2. Access Specifiers:
Member functions can be declared as public, protected, or private, which defines their access
level:
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.
Member functions ensure encapsulation by providing controlled access to the private data
members using getters and setters.
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.
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.
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.
4. Used in Operator Overloading: The this pointer is often used in operator overloading to
refer to the invoking object.
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.
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.
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.
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.
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.
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.
class ClassName {
private:
// Private members
int privateVar;
public:
};
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>
class MyClass {
private:
int data;
public:
};
int main() {
MyClass obj(42);
return 0;
Advantages:
Disadvantage:
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 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:
// 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) {
};
class ClassName {
Arithmetic Operators: +, -, *, /, %
Relational Operators: ==, !=, <, >, <=, >=
Logical Operators: &&, ||, !
Bitwise Operators: &, |, ^, ~, <<, >>
Assignment Operators: =, +=, -=, *=, /=
Unary Operators: ++, --, -, +
Other Operators: [], (), ->, new, delete.
Advantages:
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.