Unit - I, II Notes
Unit - I, II Notes
II SEMESTER
UNIT – I
Object-Oriented Programming Concepts
Object-Oriented Programming (OOP) is a paradigm centered on objects and their interactions
to design and program applications. It addresses software complexity by emphasizing
reusability, scalability, and efficiency. Let’s explore its core concepts in depth:
1. Complexity in Software Development
As software systems grow, their complexity increases exponentially due to various factors:
Feature Complexity: Adding more features increases interdependencies.
Scalability: Systems need to accommodate increasing amounts of data or users.
Maintenance: Updating, debugging, or enhancing software can become daunting.
Human Understanding: Larger systems are harder for individuals or teams to
comprehend.
Without proper structuring and methodologies, managing such complexities can lead to issues
like:
Higher error rates
Increased development and maintenance costs
Difficulty in scaling the software
2. The Need for Object-Orientation
Traditional procedural programming approaches can struggle with complex systems due to
their linear and monolithic nature. Object-oriented programming provides solutions:
ARTS AND SCIENCE, PODHATTOORPET - 631208
Real-world Modeling: Software can mirror real-world objects and their interactions.
Encapsulation: Hides internal details, exposing only necessary functionalities.
Reuse and Modularity: Components can be reused in other systems, reducing
redundancy.
Scalability and Maintainability: Clear structure allows easier scaling and updating.
OOP helps manage complexity by dividing the software into manageable, reusable, and
interactive parts.
3. Key Concepts of Object-Oriented Programming
a. Abstraction
Definition: Abstraction involves hiding unnecessary details while exposing only the
essential features of an object.
Purpose: Simplifies the interface for the user, focusing on "what" an object does rather
than "how" it does it.
Example: Consider a car. You interact with the accelerator, brakes, and steering, but you
don’t need to know how the engine or transmission works internally.
In Software: In programming, abstraction can be achieved using:
o Abstract Classes: Classes that cannot be instantiated but define a template for
derived classes.
o Interfaces: Contracts that enforce implementing certain methods.
b. Encapsulation
Definition: Encapsulation is the practice of bundling data (attributes) and methods (functions)
that operate on the data into a single unit, typically a class.
• Purpose:
o Restricts direct access to some of an object's components.
o Protects the integrity of the data by allowing controlled access via getters and
setters.
Example: A bank account object might encapsulate the account balance, exposing
methods like deposit() and withdraw() but hiding the internal logic of these methods.
In Software: Encapsulation is implemented using:
Access Modifiers: Public, private, and protected in languages like Java, C++, and Python.
c. ModularityJAY SHANKAR,M.SC., M.PHIL. ASSISTANT PROFESSOR, DEPARTMENT OF COMPUTER SCIENCE, E.
SBRMANIAM
d. Hierarchy
Definition: Hierarchy refers to the organization of classes in a parent-child structure,
allowing inheritance and polymorphism.
• Purpose:
o Promotes code reuse by enabling derived classes to inherit attributes and
methods from base classes.
o Encourages the creation of a clear relationship between objects.
Example: In an organization, a Manager class might inherit from an Employee class,
adding specific functionalities like assignTask() while retaining common attributes like
name and ID.
• In Software:
o Inheritance: Enables classes to derive properties and behavior from existing
classes.
o Polymorphism: Allows objects to take on many forms, such as having multiple
methods with the same name but different implementations.
4. How OOP Concepts Address Complexity
a. Real-world Simulation
OOP mirrors real-world entities, making it easier for developers to conceptualize and design
complex systems.
b. Scalability
The modularity and hierarchy provided by OOP make it easier to expand systems without
disrupting existing functionalities.
c. Code Reusability
Inheritance and polymorphism allow developers to reuse code across different parts of the
system, saving time and effort.
d. Maintainability
Encapsulation and abstraction help isolate changes. For example, altering the internal logic of a
class does not affect other parts of the system as long as the interface remains unchanged.
Basic Elements of C++: Classes and Objects
C++ is an object-oriented programming language that centers around the concept of classes
and objects. These elements form the foundation of Object-Oriented Programming (OOP) in C+
+.
1. Classes Definition
A class is a blueprint or template for creating objects. It defines the properties (attributes) and
behaviors (methods) that the objects of the class will have.
Key Features
Encapsulation: Combines data and methods in a single unit.
Abstraction: Provides a simplified interface for interacting with objects.
Modularity: Encourages organized and reusable code.
Syntax:
class ClassName {
// Access specifiers: public, private, protected
public:
// Attributes (data members)
int attribute;
// Methods (member functions)
void display() {
cout << "Attribute: " << attribute << endl;
}
};
Example:
class Car {
public:
string brand;
int speed;
void showDetails() {
cout << "Brand: " << brand << ", Speed: " << speed << " km/h" << endl;
}
};
2. Objects Definition
An object is an instance of a class. It is a concrete entity created using the class blueprint.
Objects hold specific values for the attributes defined in the class.
Key Features
Real-world Representation: Objects represent entities with attributes and behaviors.
Memory Allocation: When an object is created, memory is allocated to store its attributes.
Creating Objects
Objects are created using the class name.
Syntax
ClassName objectName;
C++ Program: Class and Object Example
#include <iostream>
#include <string> using
namespace std;
// Define a class class Person {
public:
// Attributes
string name;
int age;
// Method to set data
void setData(string personName, int personAge)
{ name = personName;
age = personAge;
}
// Method to display data
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
// Create objects of the Person class
Person person1, person2;
// Set data for person1
person1.setData("Vijay Shankar E S", 32);
// Set data for person2
int main()
{ Employee emp1;
// Using public methods to set and display details
emp1.setDetails("E.S.Vijay Shankar", 32);
emp1.displayDetails();
return 0;
}
Output:
Employee Name: E.S.Vijay Shankar
Employee Age: 32
3. Static Members in C++
Static members are shared among all objects of a class. They include:
Static Data Members: A single copy of the variable is shared across all objects.
Static Member Functions: Can be called without creating an object of the class and can
access only static data members.
Key Features
1. Shared Memory: Static members are shared and exist independently of any object.
2. Class-Level Scope: Accessed using the class name or an object.
3. Initialization: Static data members must be initialized outside the class.
Example: Static Data Members and Member Functions
#include iostream> using
namespace std; class
Counter { private:
static int count; // Static data member (shared across all objects)
public:
// Increment the counter
void increment() {
count++;
}
// Static member function to access the static variable
static int getCount() {
return count;
}
};
// Define and initialize static data member
int Counter::count = 0;
int main()
{ Counter c1, c2;
// Increment counter using objects
c1.increment();
c2.increment();
// Access static member function without creating an object
cout << "Current Count: " << Counter::getCount() << endl;
return 0;
}
Output:
Current Count: 2
4. Key Points
Private Access Specifier:
Protects data members from direct access.
Example: private int age;
Access through public member functions like setAge() or getAge().
Public Access Specifier:
Allows direct access to members.
Example: public void showDetails();
Static Members:
Declared using the static keyword.
Useful for data or functions shared across all objects of a class.
Example:
Examples
Default Constructor
#include <iostream>
using namespace std;
class Person {
public:
Person() {
cout << "Default Constructor Called" << endl;
}
};
int main() {
Person p1; // Default constructor invoked
return 0;
}
Parameterized Constructor
#include <iostream> using
namespace std;
class Person { private:
string name; int age;
public:
// Parameterized Constructor
Person(string n, int a) {
name = n;
age = a;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
Person p1("Alice", 25);
p1.display();
return 0;
}
Copy Constructor
#include iostream> using
namespace std;
class Person {
public:
string name;
int age;
// Parameterized Constructor
Person(string n, int a) : name(n), age(a) {}
// Copy Constructor
Person(const Person &p) {
name = p.name; age
= p.age;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
Person p1("Alice", 25);
Person p2 = p1; // Copy constructor invoked
p2.display();
return 0;
}
2. Singleton Class
Definition
A singleton class ensures that only one instance of the class is created throughout the program.
This is commonly used for managing global states or resources like database connections.
Key Features
Private constructor: Prevents direct instantiation.
Static instance: Ensures a single instance.
Public static method: Provides access to the instance.
Example
#include iostream>
using namespace std;
class Singleton {
private:
static Singleton *instance;
// Static instance int data;
// Private Constructor
Singleton() {
data = 0;
}
public:
// Static method to provide access to the instance
static Singleton *getInstance() {
if (instance == nullptr)
{ instance = new Singleton();
}
return instance;
}
void setData(int value)
{ data = value;
}
int getData()
{ return data;
}
};
Example
#include <iostream> using
namespace std; class
Person {
public:
Person() {
cout << "Constructor Called" << endl;
}
Person() {
cout << "Destructor Called" << endl;
}
};
int main() {
Person p1; // Constructor invoked
cout << "Inside main function" << endl;
return 0; // Destructor invoked automatically
}
Output:
Constructor Called
Inside main function
Destructor Called
Unit - II
Friend Functions and Friend Classes in C++
In C++, friend functions and friend classes allow one class to grant access to its private and
protected members to another function or class. These features provide controlled access to
otherwise inaccessible parts of a class.
1. Friend Function
Definition
A friend function is a non-member function that has access to the private and protected
members of a class. It is declared using the friend keyword within the class.
Key Features
Not a member of the class.
Can access private and protected members of the class it is a friend of.
Declared inside the class but defined outside the class.
Can be a normal function or a member of another class.
Syntax
class ClassName {
private:
int privateData;
public:
friend void friendFunction(ClassName obj); // Declaration of friend function
};
Example:
#include <iostream>
using namespace std;
class Box {
private:
int length;
public:
Box(int l) : length(l) {}
// Friend function declaration
friend void displayLength(Box b);
};
Box b1(10);
displayLength(b1); // Friend function can access private members
return 0;
}
Output:
Length of the box: 10
Explanation:
The displayLength function is not a member of the Box class.
By declaring it as a friend, it can access the private member length.
2. Friend Class
Definition
A friend class is a class that has access to the private and protected members of another class.
Friendship is granted by the target class using the friend keyword.
Key Features
A friend class can access all private and protected members of the granting class.
Friendship is not mutual; if Class A is a friend of Class B, Class B does not automatically
become a friend of Class A.
Syntax
class ClassName {
private:
int privateData;
friend class FriendClassName; // Declaration of friend class
};
Example
#include <iostream> using
namespace std;
class Engine {
private:
int horsepower;
public:
Engine(int hp) : horsepower(hp) {}
// Declare Car as a friend class
friend class Car;
};
class Car {
public:
void showEngineDetails(Engine e) {
cout << "Engine Horsepower: " << e.horsepower << endl;
}
};
int main() {
Engine engine(200); Car car;
car.showEngineDetails(engine); // Car has access to Engine's private data
return 0;
}
Output:
Engine Horsepower: 200
Explanation:
Car is a friend class of Engine.
Car can access the private member horsepower of Engine.
3. Friend Function in Multiple Classes
A single function can be declared as a friend of multiple classes to allow access to their private
members.
Example
#include <iostream> using
namespace std; class ClassA {
private:
int dataA;
public:
ClassA(int a) : dataA(a) {}
friend void showData(ClassA a, ClassB b);
};
class ClassB { private:
int dataB;
public:
ClassB(int b) : dataB(b) {}
friend void showData(ClassA a, ClassB b);
};
void showData(ClassA a, ClassB b) {cout << "Data from ClassA: " << a.dataA << endl; cout <<
"Data from ClassB: " << b.dataB << endl;
}
int main() {
ClassA objA(10); ClassB
objB(20); showData(objA,
objB); return 0;
}
Output:
Data from ClassA: 10
Data from ClassB: 20
Explanation:
showData is a friend of both ClassA and ClassB, allowing it to access private members of both
classes.
Key Differences between Friend Function and Friend Class
Feature Friend Function Friend Class
Scope A single function Entire class
Access Can access private/protected Can access all private/protected
members members
Declaration Declared as friend in the class Entire class is declared as friend
Granularity More fine-grained control Provides broader access to private
members
int main() {
// Create an array of Student objects
Student students[3];
// Set data for each student
students[0].setData("Lokesh", 20);
students[1].setData("Vijay", 21);
students[2].setData("Shankar", 22);
return 0;
}
Output:
Name: Vijay, Age: 20
Explanation:
The pointer ptr points to the student object.
Members of the object are accessed using the arrow operator (->).
Dynamic Allocation of Objects
Objects can also be dynamically allocated using the new operator.
Example
#include <iostream>
using namespace std;
class Student {
private:
string name;
int age;
public:
int main() {
Student *student = new Student; // Dynamically allocate memory for object
void display() {
cout << "Name: " << this->name << ", Age: " << this->age << endl;
}
};
int main() {
Student student;
student.setData("Rama", 22);
student.display();
return 0;
}
Output:
Name: Rama, Age: 22
Explanation:
The this pointer resolves the naming conflict between the member variables (name,
age) and the parameters (name, age).
Returning this Pointer
The this pointer can be used to return the current object, enabling function chaining.
Example
#include <iostream>
Key Functions
new: Allocates memory for a variable or array on the heap.
delete: Frees dynamically allocated memory.
new[] and delete[]: Used for allocating and deallocating arrays.
3. Namespaces in C++
Definition: A namespace is a feature in C++ that allows you to group related classes, functions,
variables, and other entities into a named scope to avoid name conflicts. It is particularly
useful in large projects or when using libraries.
Key Features
Helps organize code and prevent name collisions.
Can be nested and even aliased.
Allows you to control the scope of variables and functions.
Syntax
namespace MyNamespace {
// Class, function, or variable declarations
int value = 10;
void display() {
cout << "Value: " << value << endl;
}
}
Example: Basic Namespace Usage
#include iostream> using
namespace std;
// Declare a namespace
namespace MyNamespace {
int value = 100;
void display() {
cout << "Value inside MyNamespace: " << value << endl;
}
}
int main() {
// Accessing the function and variable from the namespace
MyNamespace::display();
.S.VIJAY SHANKAR,M.SC., M.PHIL.
cout << "Accessing value directly from namespace: " << MyNamespace::value << endl;
return 0;
}
Output:
Value inside MyNamespace: 100
Accessing value directly from namespace: 100
Explanation:
The MyNamespace namespace groups the variable value and function display.
You can access the members of a namespace by using the scope resolution operator (::).
Using namespace Alias
Sometimes namespaces can have long names, and using an alias can make the code
more readable.
#include <iostream>
Explanation:
The alias MN is used to access MyNamespace members, making the code cleaner and
more concise.
Namespace in Standard Library (std)
C++'s Standard Library uses the std namespace for most of it components.
For example:
# include <iostream>
#include <string> using
namespace std;
int main() {
string str = "Hello, World!";
cout << str << endl;
return 0;
}
Explanation:
The std namespace contains common standard functions and objects like cout, cin, and
string. By using using namespace std;, we avoid needing to write std::cout and
std::string every time.
Function Overloading:
Function Overloading is defined as the process of having two or more function with the same name, but
different in parameters is known as function overloading in C++. In function overloading, the function is
redefined by using either different types of arguments or a different number of arguments. It is only
through these differences compiler can differentiate between the functions.
methods,
constructors, and
indexed properties
Types of overloading in C++ are:
Function overloading
Operator overloading
#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Output:
30
55
Function Overloading and Ambiguity
When the compiler is unable to decide which function is to be invoked among the overloaded function, this
situation is known as function overloading.
When the compiler shows the ambiguity error, the compiler does not run the program.
o Type Conversion.
o Function with default arguments.
o Function with pass by reference.