Unit-II Object Class & Features
Subject Code:-CS-305 & AL-305
SUBJECT:- OOPM
By:- Adarsh Raushan
Asst. Professor
CSE Dept.,LNCT Bhopal
Encapsulation
► Encapsulation :- Encapsulation is one of the four fundamental principles of
Object-Oriented Programming (OOP), alongside inheritance, polymorphism, and
abstraction. It refers to the bundling of data (attributes) and methods (functions) that
operate on that data into a single unit called a class. Furthermore, encapsulation restricts
direct access to some of an object’s components, which is a means of preventing
unintended interference and misuse of the methods and data.
Benefits of Encapsulation:
► Improved Maintainability: By hiding the internal state and requiring all interactions
to occur through methods, the implementation can change without affecting other parts
of the code.
► Enhanced Security: Data hiding helps prevent unauthorized access and modification
of an object’s state.
► Controlled Access: Getters and setters can enforce rules for accessing and modifying
data, allowing for validation or other logic to be applied before a change is made.
► Modularity: Classes can be developed and tested independently, leading to cleaner,
more manageable code.
Data Abstraction
► Data Abstraction:-Data Abstraction is a fundamental concept in Object-Oriented
Programming (OOP) that focuses on hiding the complex reality while exposing only the
necessary parts of an object. It allows programmers to deal with ideas rather than
specific implementations, facilitating simpler interaction
Concepts of Data Abstraction:
► Hiding Complexity:- Data abstraction allows developers to hide the internal
workings and implementation details of a class or object. Users interact with the object
using a defined interface without needing to understand the underlying complexity.
► Interface vs. Implementation:-The interface defines what operations can be
performed on the data (through public methods), while the implementation details are
hidden from the user. This separation simplifies the user's interaction with the object.
► Abstract Classes and Interfaces:-In many programming languages, data abstraction
is implemented using abstract classes and interfaces. An abstract class can define some
methods (with or without implementation) and can’t be instantiated directly. Interfaces
provide a way to define methods that must be implemented by derived classes,
enforcing a contract for the class behavior. with objects.
Data Abstraction
► #include <iostream>
► using namespace std;
► Shape {
► public:
► virtual void draw() = 0;
► };
► Circleclass Circle : public Shape {
► public:
► void draw() override
► {
► cout << "Drawing a Circle." << endl
► ;}
► };
► Rectangleclass Rectangle : public Shape {
► public:
► void draw() override {
► cout << "Drawing a Rectangle." << endl; }};
► pointervoid renderShape(Shape* shape)
► {
Objects
► In Object-Oriented Programming (OOP), objects are the central concept. They represent
real-world entities or abstract concepts in a program. Each object is an instance of a class, which
serves as a blueprint for creating objects. OOP is designed to organize software design around data,
or objects, rather than functions and logic.
► Concepts of Objects in OOP
► Attributes (Fields or Properties): These are the data stored within an object. Each object can
have its own set of attributes that describe its characteristics. For example, a Car object might have
attributes like color, make, model, and year.
► Methods (Functions): These are functions associated with an object that define its behavior.
Methods can manipulate the object’s attributes or perform operations. For instance, a Car object
might have methods like drive(), brake(), and refuel().
► State: The state of an object refers to the values of its attributes at any given time. An object’s
state can change as it interacts with other objects or responds to methods.
► Identity: Every object has a unique identity, which distinguishes it from other objects, even if
two objects have the same attribute values.
► Encapsulation: Objects encapsulate data and methods that operate on that data. This ensures
that the internal workings of the object are hidden from the outside world, allowing only controlled
access through methods.
► Classes: A class is a blueprint for creating objects. It defines the attributes and methods that the
objects of the class will have. An object is an instance of a class.
Types of Objects
► Global Objects:- Objects declared outside any function have global scope and
available throughout the entire program.
► Static Objects:- Objects declared as static inside a function or class to retain their value
between function calls.
► Dynamic Objects:- Objects that are created at runtime using dynamic memory
allocation (new operator) and exist until they are explicitly deleted.
Types of Objects:- Example Program
► #include <iostream>
► using namespace std;
► class MyClass
► {
► public:
► int id;
► MyClass(int x) : id(x)
► {
► cout << "Object with id " << id << " is created." << endl;
► }
► ~MyClass()
► { cout << "Object with id " << id << " is destroyed." << endl;
► }
► void display()
► {
► cout << "Object id: " << id << endl;
► }}
► MyClass globalObj(1);
► int main()
► {
► cout << "In main function..." << endl;
Class
► Class:- In Object-Oriented Programming (OOP), a class is a blueprint or a template for creating objects
(instances). It defines the attributes (data) and methods (functions) that the objects created from the class will
have. Classes are a fundamental building block in OOP and encapsulate data and behavior, allowing for modular
and organized programming.
Concepts of a Class in OOP
1. Class Definition:- A class defines the properties (also called attributes or data members) and behaviors (also
called methods or functions) that the objects created from the class will have.
► The class itself does not represent real-world entities, but the objects (instances) created from the class
represent real-world entities.
2. Objects:-An object is an instance of a class. When you create an object, you are bringing the class to life,
initializing it with specific values.
► Each object can have its own set of attributes (values), but all objects of the class share the same behaviors
(methods).
3. Attributes (Data Members):-These are variables that hold the data for an object. Attributes can be private or
public. In many languages, attributes are stored within the __init__ (constructor) method of the class.
► Example: make, model, and year are attributes of the Car class.
4. Methods (Member Functions):- Methods define the behaviors or actions that an object can perform. They are
functions that operate on the object’s data.
► Example: start_engine() and stop_engine() are methods of the Car class that dictate what actions a car can
perform.
Instance
► In C++, an instance refers to a specific object created from a class. When a class is
defined, it acts as a blueprint, but no memory is allocated for the class itself. When an
object of that class is created, memory is allocated, and that specific object is referred to
as an instance of the class.
► A class defines a data type and its associated functions (methods).
► An instance is a concrete manifestation of a class, representing a specific entity with its
own data (state) in memory.
► Multiple instances (objects) of the same class can exist, each with its own set of
member variables.
Instance
► #include<iostream>
► using namespace std;
► class Car
► {
► public:
► string brand;
► string model;
► int year;
► Car(string b, string m, int y)
► {
► brand = b;
► model = m;
► year = y;
► }
► void display()
► {
Static Member
► In C++, the static keyword can be applied to variables, members, and functions in a
class.
► We can define class members static using member of a class as static. It means no
matter how many objects are created there is only one copy of static member.
► A Static member is shared by all objects of a class. All static data is initialized to zero
when the first object is created , if no other initialization is present. We can’t put it in
the class definition but it can be initialized outside the class.
► Static Variable:- When a variable is declared as static, space for it gets allocated for the
lifetime of the program. Even if the function is called multiple times, space for the static
variable is allocated only once and the value of the variable in the previous call gets
carried through the next function call.
Static Variable
► #include <iostream>
► #include <string>
► using namespace std;
► void demo()
► {
► static int count = 0;
► cout << count << " ";
► count++;
► }
► int main()
► {
► for (int i = 0; i < 5; i++)
► demo();
► return 0;
► }
Static Member Function
► By declaring a function member as static, you make it independent of any particular
object of the class. A static member function can be called even if no objects of the class
exist and the static functions are accessed using only the class name and the scope
resolution operator ::.
► A static member function can only access static data member, other static member
functions and any other functions from outside the class.
► Static member functions have a class scope and they do not have access to the this
pointer of the class. You could use a static member function to determine whether some
objects of the class have been created or not.
Static Member Function
► #include <iostream>
► using namespace std;
► class Box
►{
► public:
► static int objectCount;
► Box(double l = 2.0, double b = 2.0, double h = 2.0)
►{
► cout <<"Constructor called." << endl;
► length = l;
► breadth = b;
► height = h;
► objectCount++;
►}
► double Volume()
►{
► return length * breadth * height;
►}
► static int getCount()
► { return objectCount;
►}
Constructor
► A constructor is a special member function that is called automatically when an
object is created.
► In C++, a constructor has the same name as that of the class, and it does not
have a return type.
class AIML
{
public:
// create a constructor
AIML()
{
// code
}
};
Default Constructor
► A constructor with no parameters is known as a default
constructor.
► #include <iostream>
► using namespace std;
► // declare a class
► class Wall {
► private:
► double length;
► public:
► // default constructor to initialize variable
► Wall()
► : length{5.5} {
► cout << "Creating a wall." << endl;
► cout << "Length = " << length << endl;
► }
Parameterized Constructor
► In C++, a constructor with parameters is known as a parameterized constructor. This is the preferred method to
initialize member data.
► #include <iostream>
► using namespace std;
► // declare a class
► class Wall {
► private:
► double length;
► double height;
► public:
► // parameterized constructor to initialize variables
► Wall(double len, double hgt)
► : length{len}
► , height{hgt} {
► }
► double calculateArea() {
► return length * height;
► }
► };
Copy Constructor
► The copy constructor in C++ is used to copy data from one object to another.
► #include <iostream>
► using namespace std;
► class Wall {
► private:
► double length;
► double height;
► public:
► Wall(double len, double hgt)
► : length{len}
► , height{hgt} {
► }
► Wall(const Wall& obj)
► : length{[Link]}
► , height{[Link]} {
► }
► double calculateArea() {
► return length * height;
► }
Dynamic Constructor
► The constructor which allocates block of memory that can accessed by the
objects at run time is called Dynamic Constructor. In a simple terms , a
Dynamic Constructor is used to dynamically initialize the objects, that is
memory is allocated at run time.
► To define a dynamic constructor in C++, the new keyword is used. New is a
keyword in c++ that is used for dynamic allocation of memory and used for
dynamically initializing objects.
Dynamic Constructor
► #include<iostream>
► using namespace std;
► class DynamicArray
► {
► private:
► int* arr;
► int size;
► public:
► DynamicArray(int s)
► {
► size = s;
► arr = new int[size];
► cout << "Array of size " << size << " created dynamically." << endl;
► }
► void inputArray()
► {
► cout << "Enter " << size << " elements: ";
► for(int i = 0; i < size; i++)
► {
► cin >> arr[i];
► }
► }
► void displayArray() const
► {
Constructor Overloading
► Constructors can be overloaded in a similar way as function overloading.
► Overloaded constructors have the same name (name of the class) but the different number of arguments.
Depending upon the number and type of arguments passed, the corresponding constructor is called.
► // C++ program to demonstrate constructor overloading
► #include <iostream>
► using namespace std;
► class Person {
► private:
► int age;
► public:
► // 1. Constructor with no arguments
► Person() {
► age = 20;
► }
► // 2. Constructor with an argument
► Person(int a) {
► age = a;
► }
► int getAge() {
► return age;
Destructor
► In Object-Oriented Programming (OOP), a destructor is a special member function that is automatically called when an object
goes out of scope or is explicitly deleted. Its primary purpose is to free up resources that the object may have acquired during
its lifetime, such as dynamically allocated memory, file handles, or network connections.
► #include <iostream>
► using namespace std;
► class MyClass
► {
► private:
► int* data;
► MyClass(int size)
► {
► data = new int[size];
► cout << "Constructor: Allocated memory for " << size << " integers." << endl;
► }
► ~MyClass()
► {
► delete[] data;
► cout << "Destructor: Deallocated memory." << endl;
► }
► void setValue(int index, int value)
► {
► data[index] = value;
Access Modifiers
► Access Modifiers or Access Specifiers in a class are used to assign the
accessibility to the class members, i.e., they set some restrictions on the class
members so that they can’t be directly accessed by the outside functions.
► There are 3 types of access modifiers available in C++:
► Public
► Private
► Protected
Access Modifiers
► Public:- Public: All the class members declared under the public specifier will
be available to everyone. The data members and member functions declared as
public can be accessed by other classes and functions too. The public members
of a class can be accessed from anywhere in the program using the direct
member access operator (.) with the object of that class.
► Private:- The class members declared as private can be accessed only by the
member functions inside the class. They are not allowed to be accessed directly
by any object or function outside the class. Only the member functions or the
friend functions/ friend class are allowed to access the private data members of
the class.
► Protected:-The protected access modifier is similar to the private access
modifier in the sense that it can’t be accessed outside of its class unless with
the help of a friend class. The difference is that the class members declared as
Protected can be accessed by any subclass (derived class) of that class as well.
Public Access Modifiers
#include<iostream>
using namespace std;
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
}
};
int main()
{
Circle obj;
[Link] = 5.5;
cout << "Radius is: " << [Link] << "\n";
cout << "Area is: " << obj.compute_area();
Private Access Modifiers
#include<iostream>
using namespace std;
class Circle
{
private:
double radius;
public:
double compute_area()
{
return 3.14*radius*radius;
};
int main()
{
Circle obj;
[Link] = 1.5;
cout << "Area is:" << obj.compute_area();
return 0;
}
Protected Access Modifiers
#include <bits/stdc++.h>
using namespace std;
Parent
{
protected:
int id_protected;
};
class Child : public Parent
{
public:
void setId(int id)
{
id_protected = id;
}
void displayId()
{
cout << "id_protected is: " << id_protected << endl;
Friend Class & Function
► A friend class can access private and protected members of other classes in which it is
declared as a friend. It is sometimes useful to allow a particular class to access private
and protected members of other classes.
► We can declare a friend class in C++ by using the friend keyword.
► Syntax: friend class class_name;
► Like a friend class, a friend function can be granted special access to private and
protected members of a class in C++. They are not the member functions of the class
but can access and manipulate the private and protected members of that class for
they are declared as friends.
► A friend function can be:
► A global function
► A member function of another class
► Syntax:- friend return_type function_name (arguments); // for a global
function
or
friend return_type class_name::function_name (arguments); // for a member
function of another class
Friend Function
► #include <iostream>
► using namespace std;
► Box {
► private:
► double width;
► public:
► Box(double w) : width(w) {}
► friend void displayWidth(Box box);
► };
► void displayWidth(Box box)
► {
► cout << "Width of box: " << [Link] << endl;
► }
Friend Class
► // C++ program to demonstrate the working of friend class
► #include <iostream>
► using namespace std;
► // forward declaration
► class ClassB;
► class ClassA {
► private:
► int numA;
► // friend class declaration
► friend class ClassB;
► public:
► // constructor to initialize numA to 12
► ClassA() : numA(12) {}
► };
► class ClassB {
► private:
► int numB;
► public:
► // constructor to initialize numB to 1
Message Passing
► In OOP ,Message Passing refers to the process of objects communicating with each
other by invoking methods or functions. It is fundamental concepts where objects
send and receive information(messages) to interact and collaborate to perform tasks.
Each object can invoke methods on other objects to perform actions or to get data. In
most OOP languages , message passing essentially by calling methods (function) of
objects.
► Message Passing encapsulates data and behavior in objects , encouraging modularity
and separation of concerns, which are key benefits of OOP.
► Object:- The entity that sends or receives messages.
► Message:- A request for an object to invoke a method.
► Method:- The function that defines the objects behavior.
► Sender:- The object that sends the message.
► Receiver:- The object that receives the message.
► Message Content:- The information passed, such as arguments or data when
invoking a method.
Message Passing
► #include <iostream>
► using namespace std;
► class Rectangle {
► private:
► double length;
► double width;
► public:
► Rectangle(double l, double w) : length(l), width(w) {}
► double calculateArea()
► {
► return length * width;
► }
► friend class Display;
► };
► class Display {
► public:
► void showArea(Rectangle rect)