M2 oops
M2 oops
• 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?
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;
Car myCar;
myCar.speed = 100;
myCar.displaySpeed();
int main() {
// Create an object of the `Book` class
Book myBook;
return 0;
Example 2 class and object - Student
#include <iostream>
using namespace std;
int main() {
// Create an object of the `Student` class
Student student1;
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
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;
}
};
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:
• 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;
};
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 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 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
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.
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};
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
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).
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
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.
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
};
int main() {
Box box(10);
showWidth(box); // Calling friend function
return 0;
When to Use Friend Functions
class Complex {
private:
public:
cout << real << " + " << imag << "i" << endl;
};
int main() {
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