KEMBAR78
Unit - I, II Notes | PDF | Object Oriented Programming | Class (Computer Programming)
0% found this document useful (0 votes)
47 views37 pages

Unit - I, II Notes

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts using C++, detailing its core principles such as abstraction, encapsulation, modularity, and hierarchy. It explains how these concepts help manage software complexity, enhance scalability, and promote code reusability through practical examples and syntax. Additionally, it covers fundamental C++ elements like classes, objects, access specifiers, constructors, destructors, and the singleton pattern.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views37 pages

Unit - I, II Notes

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts using C++, detailing its core principles such as abstraction, encapsulation, modularity, and hierarchy. It explains how these concepts help manage software complexity, enhance scalability, and promote code reusability through practical examples and syntax. Additionally, it covers fundamental C++ elements like classes, objects, access specifiers, constructors, destructors, and the singleton pattern.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

[E.S.

VIJAY SH ARTS AND SCIENCE, PODHATTOORPET - 631208


Subject Name: Object Oriented Programming using C++
Subject Code: 135E2A

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

MEMORIAL COLLEGE OF ARTS AND SCIENCE, PODHATTOORPET - 631208

 Definition: Modularity refers to dividing a software program into smaller, self-


contained, and reusable components (modules).
• Purpose:
o Facilitates development, testing, and debugging by isolating changes.
o Enhances collaboration as different teams can work on separate modules.
 Example: A library management system might have separate modules for
UserManagement, BookCatalog, and BorrowingSystem.
 In Software: Modules in OOP are typically represented as classes or packages, allowing
developers to structure code logically.

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

person2.setData("Kandhasamy E A", 47);


// Display details of person1
cout << "Person 1 Details:" << endl;
person1.display();
// Display details of person2
cout << "\nPerson 2 Details:" << endl;
person2.display();
return 0;
}
Output:
Person 1 Details:
Name:Vijay Shankar E S
Age: 32
Person 2 Details:
Name: Kandhasamy
Age: 47
Explanation of the Program
• Class Definition:
o The Person class has two attributes: name (string) and age (integer).
o The class contains two methods:
 setData: Sets the values of name and age.
 display: Prints the values of name and age.
• Object Creation:
o Two objects, person1 and person2, are created from the Person class.
• Setting Attributes:
o The setData method is called to assign values to the name and age attributes of
each object.
• Displaying Data:
o The display method is called to print the details of each object.
Data Members and Member Functions in C++
In C++, data members are variables that hold the data (attributes) of a class, and member
functions are methods that operate on those data members. Together, they define the
properties and behavior of a class.
1. Access Specifiers
C++ provides access specifiers to control the visibility and accessibility of data members and
member functions. There are three primary access specifiers:
a. Public
 Members declared as public are accessible from outside the class.
 Typically used for methods or data members that need to be accessed directly by objects.
b. Private
 Members declared as private are accessible only within the class itself.
 Typically used to protect sensitive data and prevent unauthorized access.
c. Protected
 Members declared as protected are accessible within the class and its derived (child)
classes.
 Commonly used in inheritance scenarios.
2. Example: Data Members and Member Functions with Access Specifiers
#include iostream>
#include <string>
using namespace std;
class Employee {
private:
// Private data members string
int age;
public:
// Public member functions
void setDetails(string employeeName, int employeeAge)
{ name = employeeName;
age = employeeAge;
}
void displayDetails() {
cout << "Employee Name: " << name << endl; cout <<
"Employee Age: " << age << endl;
}
};

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:

static in total Employees;


Initialization of Static Data Members:
Must be defined outside the class.
Example:
int ClassName::staticVariable = value;
Static Member Functions:
Do not require an object to be called.
Example:
static void displayCount();
Constructors, Singleton Class, and Destructors in C++
C++ provides powerful mechanisms to manage the lifecycle of objects in Object-Oriented
Programming. These include constructors for object initialization, destructors for cleanup, and
patterns like singleton class for ensuring a single instance of a class.
1. Constructors in C++
Definition
A constructor is a special member function in C++ that is automatically called when an object of
a class is created. It initializes the object.
Key Features
Same name as the class.
No return type (not even void).
Can be overloaded.
Automatically invoked during object creation.
Types of Constructors
Default Constructor: A constructor with no parameters.
Parameterized Constructor: A constructor with parameters.
Copy Constructor: Initializes an object using another object of the same class.

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;
}
};

// Initialize static instance to nullptr


Singleton *Singleton::instance = nullptr;
int main() {
Singleton *s1 = Singleton::getInstance();
Singleton *s2 = Singleton::getInstance();
s1->setData(42);
cout << "Data from s1: " << s1->getData() << endl;
cout << "Data from s2: " << s2->getData() << endl;
return 0;
}
Output:
Data from s1: 42
Data from s2: 42
NCE, E.S. EMORIAL COLLEGE OF ARTS AND SCIENCE, PODHATTOORPET - 631208
Explanation:
Both s1 and s2 point to the same instance.
The singleton pattern ensures only one instance exists.
3. Destructors in C++
Definition
A destructor is a special member function that is automatically called when an object goes out
of scope or is explicitly deleted. It is used to release resources (e.g., memory, file handles).
Key Features
Same name as the class, preceded by a ~ symbol.
No parameters.
No return type.
One destructor per class (cannot be overloaded).

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

Key Differences between Constructors and Destructors


Feature Constructor Destructor
Purpose Initializes an object Cleans up before object deletion
Name Same as class name Same as class name, prefixed with
Parameters Can have parameters Cannot have parameters
Overloading Can be overloaded Cannot be overloaded
Invocation Automatically called Automatically called when object goes out
at object creation of scope

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);
};

// Friend function definition


void displayLength(Box b) {
cout << "Length of the box: " << b.length << endl;
}
int main() {

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

4. When to Use Friendship?


 Use friend functions or classes when a non-member or external class requires direct
access to private or protected members of another class.
 Friendship should be used sparingly to avoid breaking encapsulation.
Array of Objects, Pointer to Objects, and this Pointer in C++
C++ offers several powerful features that make working with objects flexible and efficient. This
includes creating arrays of objects, using pointers to objects, and leveraging the this pointer
for object-specific operations.
1. Array of Objects
Definition
An array of objects is a collection of objects of the same class, stored in contiguous memory
locations.
Example
#include <iostream>
using namespace std;
class Student { private:
string name; int age;
public:
void setData(string n, int a)
{ name = n;
age = a;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;L COLLEGE OF ARTS AND SCIENCE,
PODHATTOORPET - 631208
}
};

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);

// Display data for each student


for (int i = 0; i < 3; i++) {
students[i].display();
}
return 0;
}
Output:
Name: Lokesh, Age: 20
Name: Vijay, Age: 21
Name: Shankar, Age: 22
Explanation:
 students[3] is an array holding three Student objects.
 Each object is accessed using its index, just like an array of primitive data types.
2. Pointer to Objects
Definition
A pointer to an object stores the memory address of an object, allowing dynamic access to its
members.
Syntax
ClassName *ptr = &objectName;
Accessing Members
Use the arrow operator (->) to access the members of the object through a pointer.
Example
#include <iostream>
using namespace std;
class Student { private:
string name;
int age;
public:
void setData(string n, int a)
{ name = n;
age = a;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() { Student
student;
Student *ptr = &student; // Pointer to object
// Access members using pointer ptr-
>setData("Vijay", 20);
ptr->display();

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:

void setData(string n, int a)


{ name = n;
age = a;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
Student *student = new Student; // Dynamically allocate memory for object

// Access members using pointer


student->setData("Kavitha", 21);
student->display();
delete student; // Free allocated memory
return 0;
}
Output:
Name: Kavitha, Age: 21
Explanation:
 Memory is allocated dynamically for the student object.
 The delete keyword is used to release the memory.

3. This Pointer Definition


 The this pointer is an implicit pointer available in all non-static member functions of a
class. It points to the calling object and can be used to:
 Refer to the calling object explicitly.
 Resolve naming conflicts between member variables and parameters.
Example
#include <iostream>
using namespace std;
class Student {
private:
string name; int age;
public:
void setData(string name, int age) {
// Resolving conflict using 'this' pointer
this->name = name;
this->age = age;
}

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>

using namespace std;

class Student { private:


string name;
int age;
public:
Student* setName(string name) {
this->name = name;
return this;
}
Student* setAge(int age) { this->age = age;
return this;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main()
{ Student
student;
student.setName("Ragava")->setAge(20)->display(); // Function chaining
return 0;
}
Output:
Name: Ragava, Age: 20
Explanation:
Each method returns the this pointer, allowing chaining of multiple calls on the same object.
Feature Description Access Syntax
Array of Objects Collection of objects stored in objects[i].member
contiguous memory.
Pointer to Objects Pointer storing the address of an object; ptr->member
allows dynamic memory allocation and
object
access.
this Pointer Implicit pointer to the calling object; this->member
resolves conflicts and
enables method chaining.

.S.. ASSISTANT PROFESSOR, DEPARTMENT OF COMPUTER SCIENCE,


These concepts are essential for managing objects in C++, offering flexibility in memory
handling and object interaction.
References, Dynamic Memory Allocation, and Namespaces in C++
C++ provides several features for managing memory and organizing code, including references,
dynamic memory allocation, and namespaces. Let's explore these features in detail.
1. References in C++
Definition
A reference is an alias for another variable. It allows you to create a new name for an existing
variable, and any changes made to the reference will affect the original variable.
Key Features
 A reference must be initialized when it is declared.
 A reference cannot be null and must always refer to a valid object.
 A reference behaves like the original object.
Syntax
dataType& referenceName = originalVariable;
Example
#include iostream> using
namespace std; int
main() {
int a = 5;
int& ref = a; // ref is a reference to a
cout << "Original variable a: " << a << endl; cout
<< "Reference to a: " << ref << endl;
// Modifying the reference will modify the original variable
ref = 10;
cout << "After modifying reference:" << endl;
cout << "Original variable a: " << a << endl;
cout << "Reference to a: " << ref << endl;
return 0;
}
Output:
Original variable a: 5
Reference to a: 5
After modifying reference:
Original variable a: 10
Reference to a: 10
Explanation:
 The reference ref is an alias for a.
 Modifying ref also modifies the original variable a.
2. Dynamic Memory Allocation in C++
Definition
Dynamic memory allocation allows programs to allocate memory at runtime using pointers.
This is useful when the exact amount of memory required is not known at compile time.

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>

using namespace std;


// Alias for a namespace
namespace MyNamespace {
void printMessage() {
cout << "Hello from MyNamespace!" << endl;
}
}
namespace MN = MyNamespace; // Alias for MyNamespace
int main() {
MN::printMessage(); // Using the alias to access the function
return 0;
}
Output:
Hello from MyNamespace!

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.

C++ Overloading (Function and Operator)


we create two or more members having the same name but different in number or type of parameter, it is
known as C++ overloading. In C++, we can overload:

 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.

Causes of Function Overloading:

o Type Conversion.
o Function with default arguments.
o Function with pass by reference.

Operator Overloading in C++ Using Friend Function


C++'s strong and crucial Operator overloading feature enables you to modify the behaviour of built-in
operators for user-defined data types. As an object-oriented programming language, C++ has this as one
of its primary characteristics.
To simplify and improve the readability of your code, you can make your classes and objects act like
built-in data types via operator overloading. Utilizing buddy functions or member functions, you can
overload operators in C++. We will concentrate on Operator overloading utilizing buddy functions in this
extensive article.

You might also like