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

M2 oops

Oops with c++

Uploaded by

Aditi Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

M2 oops

Oops with c++

Uploaded by

Aditi Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 135

Module – 2

Classes and Objects: Declaring Objects – Defining Member


Functions – Static Member variables and functions – array of
objects –friend functions – Overloading member functions – Bit
fields and classes – Constructor and destructor with static
members. (8 Hours)
Classes and Objects in C++

• In C++, classes and objects are fundamental building blocks of object-


oriented programming.
• A class is like a blueprint for creating objects. It defines the properties
(data members) and behaviors (member functions) that an object
created from that class can have.
CLASS
• A class in programming is like a blueprint or recipe. Imagine you're
building something like a robot or an instruction guide.
• The class defines what it should have and what it can do, just like a
chef knows the ingredients and how to cook. Each time you create
something from this class (called an object), it's like making a new
robot or cooking a new dish, following that same recipe.

• In this example:
• The Chef class knows about secret ingredients (which are kept
private).
• The chef has some actions it can perform, like preparing food.
• Waiters (objects) interact with the chef to get the food prepared.
1. What is a Class?

• A class is a user-defined data type that serves as a template for


objects. It contains variables and functions that represent the
properties and actions of the object.
Introduction to Classes and Objects
•. Classes: A class is a user-defined data type that holds data and functions. It acts as a blueprint to create objects with
properties (data members) and behaviors (member functions).
•Objects: An object is an instance of a class. Each object has its own set of properties defined by the class.

class Car
{
public:
int speed;
void displaySpeed()
{
cout << "Speed: " << speed << endl;
This example defines a Car class with a public
}
};
data member speed and a member function
Car key1, key2,key3 displaySpeed. The function displays the car's
Key1.speed=100;
speed when called.
Key2. displaySpeed();
Syntax for Declaring a Class:
class ClassName
{
// Access Specifiers: public, private, protected
public:
// Data Members (Properties)
int data;

// Member Functions (Behaviors)


void showData()
{ •ClassName: The name of the class.
•Data Members: Variables inside the class that hold data specific to
// Code for function the object.
} •Member Functions: Functions inside the class that define
behaviors of the object.
};
Declaring Objects
• Once a class is defined, you can create objects to represent instances of that class.
• An object is an instance of a class. When you create an object, memory is allocated,
and you can access the class members using this object

Syntax: ClassName objectName;

Car myCar;
myCar.speed = 100;
myCar.displaySpeed();

Here, myCar is an object of the Car class. We assign a value


to myCar.speed and call myCar.displaySpeed() to output the speed.
This demonstrates how objects access class members.
Defining Member Functions
• Inside the Class: When a function is defined inside the class, it is
automatically treated as an inline function.
class Car {
public:
int speed;
void displaySpeed(); // Declared inside
{
cout << "Speed: " << speed << endl;
}
};
• Outside the Class: Use the scope resolution operator (::) to define a
function outside the class.
class Car {
public:
int speed;
void displaySpeed(); // Declared inside
};

// Defined outside the class


void Car::displaySpeed()
{
cout << "Speed: " << speed << endl;
}
Example 1 class and object
class Car
{
public:
int speed;
void displaySpeed()
{
cout << "Speed: " << speed << endl;
}
In this example:
};
•Car is the class.
•myCar is an object of the Car class.
int main() { •We set the speed of myCar and then display it
using displaySpeed().
Car myCar; // Creating an object of class Car
myCar.speed = 100; // Accessing data member
myCar.displaySpeed(); // Calling member function
return 0;
}
Example 2 class and object
#include <iostream>
using namespace std;
// Define a class named `Car`
class Car {
public:
// Attributes of the car
string color;
int speed;
// Function to display car details
void displayInfo() {
cout << "Car color: " << color << endl;
cout << "Car speed: " << speed << " km/h" << endl;
}
};
int main() {
// Create an object of the `Car` class
Car myCar;
// Set values for the car's attributes
myCar.color = "Red";
myCar.speed = 120;
// Show the car's details
myCar.displayInfo();
return 0;
}
•Class (Car): Think of a class as a blueprint or plan for something.
Here, Car is a blueprint that describes what every car should have: a
color and a speed.
•Object (myCar): An object is like a real version made from the
blueprint. myCar is an actual car that has a color and a speed.
•Attributes: Inside the Car class, color and speed are things every car
has. We can set these to different values.
•Function (displayInfo): This function is like a feature that allows us to
see the car's details.
Example 3 class and object - DOG
#include <iostream>
using namespace std;
// Define a class named `Car`
class Car {
public:
// Attributes of the car
string color;
int speed;
// Function to display car details
void displayInfo() {
cout << "Car color: " << color << endl;
cout << "Car speed: " << speed << " km/h" << endl;
}
};
int main() {
// Create an object of the `Car` class
Car myCar;
// Set values for the car's attributes
myCar.color = "Red";
myCar.speed = 120;
// Show the car's details
myCar.displayInfo();
return 0;
}
Example 3 class and object - BOOK
#include <iostream>
using namespace std;

// Define a class named `Book`


class Book {
public:
string title;
string author;

// Function to display book details


void displayInfo() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
}
};

int main() {
// Create an object of the `Book` class
Book myBook;

// Set book's attributes


myBook.title = “OPPS C++";
myBook.author = "balaguruswamy";

// Show the book's details


myBook.displayInfo();

return 0;
Example 2 class and object - Student
#include <iostream>
using namespace std;

// Define a class named `Student`


class Student {
public:
string name;
int grade;

// Function to display student details


void showInfo() {
cout << "Student Name: " << name << endl;
cout << "Grade: " << grade << endl;
}
};

int main() {
// Create an object of the `Student` class
Student student1;

// Set student's attributes


student1.name = "Alice";
student1.grade = 10;

// Display student's information


student1.showInfo();

return 0;
Class Example (Encapsulation) –The program defines a class (Chef) with a private attribute and a public method,
illustrating encapsulation.
#include <iostream>
#include <string>
using namespace std;
// Main function
// Define the Chef class int main() {
class Chef { // Create Chef object
private: Chef waiter1, waiter2, waiter3;
// Secret ingredients (only the chef knows these) DATA
string secretIngredient = "Magic Spice";

// Private method to show that only Chef knows how to use the // Waiters can request dishes to be prepared
secret ingredient cout << waiter1 << " requests a Pizza." << endl;
void useSecretIngredient() { waiter1.prepareDish("Pizza"); // Waiter1 asks chef to
cout << "Using secret ingredient: " << secretIngredient << endl; prepare pizza
}
cout << waiter2 << " requests a Pasta." << endl;
public: waiter2.prepareDish("Pasta"); // Waiter2 asks chef to
// Function to prepare food (only accessible from outside) prepare pasta
void prepareDish(string dishName) {
cout << "Chef is preparing: " << dishName << endl;
useSecretIngredient(); // Chef uses the secret ingredient return 0;
cout << dishName << " is ready!" << endl;
}
};
3. Access Specifiers

• Access specifiers in C++ determine the accessibility of class members.


There are three main access specifiers:

1.Public: Members declared as public are accessible from outside the cl


ass.
2.Private: Members declared as private are accessible only within the cl
ass.
3.Protected: Members declared as protected are accessible within the
class and by derived class.
3. Public Access Specifier:
1. Members declared as public are accessible from outside the class.
#include <iostream>
using namespace std;

class PublicExample {
public:
int publicVar;
};

int main() {
PublicExample obj;
obj.publicVar = 10; // Accessible from outside the class
cout << "Public Variable: " << obj.publicVar << endl;
return 0;
}
3. Private Access Specifier:
• Members declared as private are accessible only within the class.

#include <iostream>
using namespace std;

class PrivateExample {
private:
int privateVar;
public:
void setPrivateVar(int val) {
privateVar = val;
}
int getPrivateVar() {
return privateVar;
} };
int main() {
PrivateExample obj;
obj.setPrivateVar(20); // Accessible through public methods
cout << "Private Variable: " << obj.getPrivateVar() << endl;
return 0;
}
Protected Access Specifier:
• Members declared as protected are accessible within the class and by derived classes.
#include <iostream>
using namespace std;

class Base {
protected:
int protectedVar;
public:
Base() {
protectedVar = 30;
}
};

class Derived : public Base {


public:
void show() {
cout << "Protected Variable: " << protectedVar << endl; // Accessible in derived class
}
};

int main() {
Derived obj;
obj.show();
return 0;
}
4. Defining Member Functions
• Member functions can be defined in two ways:
1.Inside the class (inline).
2.Outside the class using the scope resolution operator ::.
Example of Defining a Function Outside the Class:
class Rectangle {
private:
int width, height;
public:
void setDimensions(int w, int h); // Declaration
int area() {
return width * height;
}
}; Here:
// Definition outside the class •setDimensions is defined outside the Rectangle class using Rectangle::.
void Rectangle::setDimensions(int w, int h) { •The function area() calculates the area of the rectangle.
width = w;
height = h;
}
int main() {
Rectangle rect;
rect.setDimensions(5, 6);
cout << "Area: " << rect.area() << endl;
return 0;
}
Key Takeaways:

• A class in C++ is a user-defined data type.


• Objects are instances of a class, representing specific entities.
• Access specifiers (public, private, protected) control access to
members.
• Member functions can be defined inside or outside the class.

• Using classes and objects effectively allows for organizing code and
representing real-world entities in programming.
Static Member Variables and Functions
• In OOP’s language, static member variables are variables that are shared among all
instances of a class.
• They are defined with the static keyword, ensuring that only one copy exists, no matter
how many objects of the class are created.

•Definition: A static member variable is shared by all objects of the class. It is declared using
the static keyword.
•Declaration: Declared using the static keyword within the class declaration, but outside any
member function. They are typically initialized outside the class definition
•Initialization: Static member variables must be defined outside the class definition and
initialized only once.
•Lifetime: They exist for the entire duration of the program.
•Access: Accessed using the class name (e.g., ClassName::staticVariable) or through an object
of the class (e.g., object.staticVariable). However, using the class name is preferred to avoid
confusion and emphasize that it's a class-level variable.
syntax
class MyClass {
public:
static int staticVar;
};

int MyClass::staticVar = 0; // Initialization outside the class definition


Static members
#include <iostream>
using namespace std;

class Counter {
public:
static int count;
Counter() {
count++; • In this example, the count variable is shared among all
} instances of the Counter class.
• Each time an object of the Counter class is created, the
}; count variable is incremented

int Counter::count = 0; // Initialize static member variable

int main() {
Counter c1, c2, c3;
cout << "Count: " << Counter::count << endl; // Output will be 3
return 0;
}
Static Member Functions

•Definition: A static member function can be called on the class itself, not on an instance
of the class. It is also declared using the static keyword.
•They are also defined using the static keyword and can only access other static member
variables and functions.

•Access: They can only access static member variables and other static member
functions.
•Usage: Useful for utility functions that do not depend on object-specific data.
Static member function
#include <iostream>
using namespace std;

class MyClass {
public:
static void display() {
cout << "Static member function called" << endl;
}
};

int main() {
MyClass::display(); // Calling static member function using class name
return 0;
}
class MyClass {
public:
static void staticFunction() {
// Can only access staticVar and other static functions
staticVar++;
}
static int staticVar;
};

int MyClass::staticVar = 0; // Initialization outside the class definition

int main() {
MyClass::staticFunction(); // Calling static function using class name
return 0;
}
• Static members are particularly useful for defining constants,
counters, or utility functions that are common to all instances of a
class.
• They help in reducing memory usage and ensuring that certain data
or functions are shared across all objects of the class.
• https://www.codewithharry.com/videos/cpp-tutorials-in-hindi-23/
Constructor
• A constructor is a special function that initializes an object when it is
created. It is automatically called when an object of the class is
instantiated.

Key Characteristics
• Same Name as Class: The constructor has the same name as the
class.
• No Return Type: Constructors do not have a return type, not
even void.
• Can Be Overloaded: You can have multiple constructors in the same
class (constructor overloading) with different parameter lists.
Types of Constructors

1.Default Constructor: Takes no arguments.


2.Parameterized Constructor: Takes one or more arguments to
initialize members.
3.Copy Constructor: Initializes an object using another object of the
same class. Its form is ClassName (const ClassName &obj).
Example of Constructors
// Copy Constructor
#include <iostream>

using namespace std;


Car(const Car &c) {
model = c.model;
class Car { year = c.year;
private:
cout << "Copy Constructor called." << endl;
string model;

int year;
}

public:
void display() const {
// Default Constructor

Car() {
cout << "Model: " << model << ", Year: " << year << endl;
model = "Unknown"; }
year = 0; };
cout << "Default Constructor called." << endl;

}
int main() {
// Parameterized Constructor Car car1; // Calls Default Constructor
Car(string m, int y) {
Car car2("Toyota", 2020); // Calls Parameterized Constructor
model = m;

year = y;
Car car3 = car2; // Calls Copy Constructor
cout << "Parameterized Constructor called." << endl;

} car1.display();
0;
car2.display();
}
car3.display();

return
Arrays in C++
• Arrays in C++ are a collection of elements of the same type stored in
contiguous memory locations.
• They allow you to store multiple values in a single variable, making it
easier to manage and manipulate data.

1.Declaration and Initialization:


1. You can declare an array by specifying the type of its elements and the number of elem
ents required.
2. You can also initialize an array at the time of declaration.
Array1
#include <iostream>
using namespace std;
int main() {
// Declaration of an array of integers with 5 elements
int numbers[5];
// Initialization of an array
int values[5] = {10, 20, 30, 40, 50};
// Accessing array elements
cout << "First element: " << values[0] << endl;
cout << "Second element: " << values[1] << endl;
// Modifying array elements
values[2] = 60;
cout << "Modified third element: " << values[2] << endl;

return 0;
}
2.Accessing Array Elements:
2. Array elements are accessed using their index, which starts from 0.
3. You can read or modify the elements using the index.
3.Looping Through Arrays:
1. You can use loops to iterate through the elements of an array.

#include <iostream>
using namespace std;

int main() {
int values[5] = {10, 20, 30, 40, 50};

// Looping through the array using a for loop


for (int i = 0; i < 5; i++) {
cout << "Element at index " << i << ": " << values[i] << endl;
}

return 0;
}
4.Multidimensional Arrays:
C++ also supports multidimensional arrays, such as 2D arrays.

#include <iostream>
using namespace std; In summary:
•Arrays are used to store multiple values
int main() { of the same type.
// Declaration and initialization of a 2D array •Elements are accessed using their index.
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}; •Loops can be used to iterate through arr
ay elements.
// Accessing elements of a 2D array •C++ supports both single-
cout << "Element at [0][0]: " << matrix[0][0] << endl; dimensional and multidimensional arrays
cout << "Element at [1][2]: " << matrix[1][2] << endl; .

return 0;
}
Array of objects
• An array of objects in C++ is a collection of objects stored in contiguous
memory locations.
• This allows you to manage multiple objects of the same class efficiently.
#include <iostream>
using namespace std;

class Student {
public:
string name;
int age;
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
} };
int main() {
// Creating an array of Student objects
Student students[3];
// Initializing the array elements
students[0].name = "Alice";
students[0].age = 20;
students[1].name = "Bob";
students[1].age = 21;
students[2].name = "Charlie";
students[2].age = 22;
// Displaying the array elements
for (int i = 0; i < 3; i++) {
students[i].display();
}
return 0;
}
Constructors and Destructors
• constructors and destructors are special functions associated with
classes that handle the creation and destruction of object.

Constructor
• A constructor is a special member function that initializes an object
when it is created.
• It has the same name as the class and does not have a return type,
not even void.
• Constructors are automatically called when an object is created.
Basic Characteristics of a Constructor

• Same Name as Class: The constructor's name is exactly the same as


the class name.
• No Return Type: Constructors don't have a return type.
• Automatic Invocation: Called automatically when an object is
created.
Example of a Constructor
#include <iostream>
using namespace std;

class Person {
private:
string name;

public:
// Constructor to initialize name
Person(string n) {
name = n;
cout << "Constructor called. Name is set to " << name << endl;
}
};

int main() {
Person p1("Alice"); // Constructor is called with name "Alice"
return 0;
}
Destructor
• A destructor is a special member function that is called automatically
when an object goes out of scope or is deleted.
• The destructor is used to release any resources that the object may
have acquired during its lifetime (like memory, files, or network
connections).

Basic Characteristics of a Destructor


• Same Name as Class with a Tilde (~): The destructor's name is the
class name prefixed by a tilde (~).
• No Parameters: Destructors do not take any parameters.
• Called Automatically: Automatically invoked when the object is
destroyed.
#include <iostream>
using namespace std;

class Person {
private:
string name;

public:
// Constructor
Person(string n) {
name = n;
cout << "Constructor called. Name is set to " << name << endl;
}

// Destructor
~Person() {
cout << "Destructor called. Cleaning up for " << name << endl;
}
};

int main() {
Person p1("Alice"); // Constructor is called here
return 0; // Destructor is called here automatically
}
Summary

• Constructor: Initializes an object when it's created. It has the same


name as the class, no return type, and can be overloaded.
• Destructor: Cleans up resources when an object is destroyed. It has
the same name as the class prefixed with ~, no parameters, and
cannot be overloaded.
Types of Constructors in C++
1.Default Constructor: No parameters. They are used to create
an object with default values.

2.Parameterized Constructor: Takes parameters. Used to create


an object with specific initial values.

3.Copy Constructor: Takes a reference to another object of the


same class. Used to create a copy of an object.
1. Default Constructor
• A default constructor is a constructor that doesn’t take any
argument. It has no parameters. It is also called a zero-
argument constructor.

Syntax of Default Constructor


• className() {
// body_of_constructor
}

The compiler automatically creates an implicit default


constructor if the programmer does not define one.
//DEFAULT CONSTROC
#include <iostream>
using namespace std;

class Car {
public:
string color;
string model;

// Default Constructor
Car() {
color = "Red";
model = "Sedan";
}
};

int main() {
Car myCar; // Calls default constructor
cout << "Color: " << myCar.color << ", Model: " << myCar.model << endl;
return 0;
}
2. Parameterized Constructor
• Parameterized constructors make it possible to pass
arguments to constructors. Typically, these arguments
help initialize an object when it is created.

Syntax of Parameterized Constructor


• className (parameters...) {
// body
}

If we want to initialize the data members, we can also use


the initializer list as shown:
• MyClass::MyClass(int val) : memberVar(val) {};
Parameterized Constructor
#include <iostream>
using namespace std;

class Car {
public:
string color;
string model;

// Default Constructor
Car() {
color = "Red";
model = "Sedan";
}
};

int main() {
Car myCar; // Calls default constructor
cout << "Color: " << myCar.color << ", Model: " << myCar.model << endl;
return 0;
}
3. Copy Constructor
• A copy constructor is a member function that initializes
an object using another object of the same class.
Syntax of Copy Constructor
• Copy constructor takes a reference to an object of the
same class as an argument.
• ClassName (ClassName &obj)
{
// body_containing_logic
}
• Just like the default constructor, the C++ compiler also
provides an implicit copy constructor if the explicit copy
constructor definition is not present.
Copy Constructor
#include <iostream>
using namespace std;

class Car {
public:
string color;
string model;

// Parameterized Constructor
Car(string c, string m) {
color = c;
model = m;
}

// Copy Constructor
Car(const Car &other) {
color = other.color;
model = other.model;
}
};

int main() {
Car originalCar("Green", "Coupe"); // Calls parameterized constructor
Car copiedCar = originalCar; // Calls copy constructor
cout << "Copied Car Color: " << copiedCar.color << ", Model: " << copiedCar.model << endl;
return 0;
}
Constructor and destructor with static members
Constructor and destructor with static members
Constructor and destructor with static members
Constructor and destructor with static members
Constructor and destructor with static members
Constructor and destructor with static members
• Object-Oriented Programming
(OOP), constructors and destructors are special member functions of
a class that handle the initialization and cleanup of objects. Here’s
how they work, especially with static members:
1. Constructor
• A constructor is a function that gets called automatically when an
object of the class is created. It initializes object members.
• Constructors do not initialize static members directly. Static members
belong to the class, not to individual objects, so they are initialized
outside the constructor using the :: scope resolution operator.
Constructor and destructor with static members

2. Destructor
• A destructor is called automatically when an object goes out of scope
or is explicitly deleted. It handles cleanup.
• Destructors also do not destroy static members because static
members are shared across all instances of the class. They persist for
the lifetime of the program or until explicitly removed or changed
Static Members
• Static members are associated with the class itself, rather than with
any particular instance.
• They are declared inside the class but defined and initialized outside.
• Static members are initialized only once, regardless of how many
objects of the class are created.
#include <iostream>
using namespace std;
class MyClass {
static int staticCounter; // Static member variable // Definition and initialization of static member
int instanceCounter; int MyClass::staticCounter = 0;
public:
// Constructor int main() {
MyClass() : instanceCounter(0) {
MyClass obj1; // Constructor called
MyClass obj2; // Constructor called
staticCounter++; // Increment static member
instanceCounter++; // Increment instance member
cout << "Current Static Counter: " <<
cout << "Constructor called. Static Counter: " << staticCounter <<MyClass::getStaticCounter()
", << endl;
Instance Counter: " << instanceCounter << endl;
}
{ // New scope
// Destructor MyClass obj3; // Constructor called
~MyClass() { } // Destructor called for obj3 when it goes out of scope
staticCounter--; // Decrement static member
cout << "Final Static Counter: " <<
cout << "Destructor called. Static Counter: " << staticCounter << endl;
} MyClass::getStaticCounter() << endl;
static int getStaticCounter() {
return 0;
}
return staticCounter; // Access static member
} };
Friend Functions in C++

• friend functions are functions that are not members of a class but are
allowed to access its private and protected members of a class.
• Friendship is not inherited and cannot be transferred.
• Declaring a function as a friend within a class allows it special access,
even though it’s defined outside the class.
Syntax of Friend Function

To declare a friend function, you use the friend keyword inside the class
declaration

class ClassName {
private:
int data;

public:
friend void FriendFunction(ClassName& obj); // friend function
declaration
};
Characteristics of Friend Functions
1.Not a Member Function: It is declared inside the class but defined
outside, and it doesn’t use the ClassName:: scope.
2.Access to Private and Protected Members: It can access private and
protected data of the class.
3.Not Called with Object: Since it's not a member function, it is not
called using an object of the class.
4.Defined Outside the Class: The definition of the friend function
happens outside of the class.
Example of Friend Function
#include <iostream>
using namespace std;

class Box {
private:
int width;

public:
Box(int w) : width(w) {} // Constructor
friend void showWidth(Box& b); // Friend function declaration
};

// Friend function definition


void showWidth(Box& b) {
cout << "Width of box: " << b.width << endl;
}

int main() {
Box box(10);
showWidth(box); // Calling friend function
return 0;
When to Use Friend Functions

1.Operator Overloading: Friend functions are commonly used for


operator overloading when two different objects need to access each
other's private data.
2.Non-Member Functions with Access: When you need a function that
is not a member of a class but still requires access to its private
members.
Example of Friend Function for Operator Overloading
#include <iostream>

using namespace std;

class Complex {

private:

int real, imag;

public:

Complex(int r, int i) : real(r), imag(i) {}

// Friend function to add two Complex numbers

friend Complex operator+(Complex const &c1, Complex const &c2);

void display() const {

cout << real << " + " << imag << "i" << endl;

};

// Overloading + operator as a friend function

Complex operator+(Complex const &c1, Complex const &c2) {

return Complex(c1.real + c2.real, c1.imag + c2.imag);

int main() {

Complex c1(3, 4), c2(1, 2);

Complex c3 = c1 + c2; // Calls friend function

c3.display();

return 0;

}
Overloading member functions
• Function Overloading is a feature in Object-Oriented Programming
that allows multiple functions with the same name but different
parameter lists (types or numbers of parameters) to coexist in the
same scope.
• In a class, this can be achieved by defining multiple member
functions with the same name but varying argument lists.
Key Points About Overloading Member
Functions
1.Same Name, Different Parameters: The functions must have the
same name but differ in the number or types of parameters.
2.Compile-Time Polymorphism: Overloading is a form of compile-time
polymorphism, where the correct function is selected based on the
arguments at compile time.
3.Return Type Cannot Differentiate: Changing only the return type is
not sufficient for overloading; the parameters must differ.
#include <iostream>
using namespace std;

class Calculator {
public:
int main() {
// Overloaded 'add' function with two integer parameters
Calculator calc;
int add(int a, int b) {
cout << "Adding two integers: " << a << " + " << b << " = ";
// Calls the 'add(int, int)' function
return a + b;
cout << calc.add(5, 10) << endl;
}
// Calls the 'add(int, int, int)' function
// Overloaded 'add' function with three integer parameters cout << calc.add(5, 10, 15) << endl;
int add(int a, int b, int c) {
cout << "Adding three integers: " << a << " + " << b << " + // Calls the 'add(double, double)' function
" << c << " = ";
cout << calc.add(3.5, 4.5) << endl;
return a + b + c;
}
return 0;
}
// Overloaded 'add' function with two double parameters
double add(double a, double b) {
cout << "Adding two doubles: " << a << " + " << b << " = ";
return a + b;
}
};
Benefits of Function Overloading

• Increased Readability: Functions that perform similar operations can


share the same name, making code easier to understand.
• Convenience: It allows you to use a single function name for different
operations, which reduces the need to remember multiple function
names.
Bit fields
• Bit fields in C++ allow you to allocate a specific number of bits for
data members within a class or struct.
• They’re commonly used when memory efficiency is a priority,
especially in systems programming, embedded systems, and
applications with limited memory resources.
Key Concepts of Bit Fields
1.Memory Efficiency: Bit fields allow you to use only as many bits as
necessary, rather than a full byte (8 bits) or an integer (32 bits). For
example, if you only need a boolean flag, you can allocate a single bit
instead of using a full int.
2.Syntax: Bit fields are defined by specifying the number of bits in
square brackets after the variable name.
3.Data Type Requirements: Bit fields are typically unsigned integers
(unsigned int), although other integral types can be used. The type
determines the storage unit but does not affect the number of bits
allocated.
4.Accessing and Modifying Bit Fields: Bit fields are accessed like
normal struct/class members, but the compiler ensures that only the
specified number of bits is used.
Defining and Using Bit Fields in Classes
#include <iostream>
using namespace std;
class StatusFlags {
public:
// Bit fields in the StatusFlags class int main() {
unsigned int isActive : 1; // Uses 1 bit to store isActive flag // Create an instance of StatusFlags with bit field values
unsigned int errorLevel : 3; // Uses 3 bits to store errorLevel (0-7 range) StatusFlags flags(true, 5, 10);
unsigned int permissions : 4; // Uses 4 bits to store permissions (0-15 range)
// Display the bit field values
// Constructor to initialize bit fields flags.displayStatus();
StatusFlags(bool active, int error, int perms)
return 0;
: isActive(active), errorLevel(error), permissions(perms) {}
}

// Function to display the values of bit fields


void displayStatus() {
cout << "Status: " << endl;
cout << " - isActive: " << isActive << endl;
cout << " - errorLevel: " << errorLevel << endl;
cout << " - permissions: " << permissions << endl;
} };
Key Limitations and Considerations
• Portability: Bit field representation and alignment can vary
between different compilers and architectures. This can
affect portability.
• No Pointers to Bit Fields: You can’t take the address of a bit
field member.
• Range Constraints: Storing values beyond the range of the
allocated bits can cause truncation.
• Efficient Only in Small Doses: Overusing bit fields may
complicate code readability and debugging, so they are best
suited for small configurations or flags.
• Bit fields can be a powerful tool for efficient memory use, particularly
in constrained environments or for managing flags, settings, or small
data fields.

You might also like