Unit 2 OOP&M
Unit 2 OOP&M
Help protect our data. A client cannot change an Account's balance if we encapsulate it.
Encapsulated classes are easier to change. We can change the privacy of the data
according to the requirement without changing the whole program by using access modifiers
(public, private, protected). For example, if a data member is declared private and we wish
to make it directly accessible from anywhere outside the class, we just need to replace the
specifier private by public.
Let's see an example of Encapsulation.
#include<iostream>
usingnamespacestd;
classRectangle
{
intlength; intbreadth; public:
voidsetDimension(intl,intb)
{ length=l;
breadth=b;
}
intgetArea()
{
returnlength*breadth;
}
};
intmain()
{
Rectanglert; rt.setDimension(7,4);
cout<<rt.getArea()<<endl; return0;
}
Data Abstraction
Data abstraction is one of the most essential and important feature of object oriented programming
in C++. Abstraction means displaying only essential information and hiding the details. Data
abstraction refers to providing only essential information about the data to the outside world, hiding
the background details or implementation.
Consider a real life example of a man driving a car.The man only knows that pressing the
accelerators will increase the speed of car or applying brakes will stop the car but he does not know
about how on pressing accelerator the speed is actually increasing, he does not know about the inner
mechanism of the car or the implementation of accelerator, brakes etc in the car. .
Advantages of Data Abstraction:
Can change internal implementation of class independently without affecting the user.
Classes: Identifying classes and candidate for classes Attribute and services
Class: The building block of C++ that leads to Object Oriented programming is a Class.
The Class representation of objects and the sets of operations that can be applied to such
objects.
Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions defines
the properties and behavior of the objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage etc and
member functions can be apply brakes, increase speed etc.
The primary purpose of a class is to hold data/information. This is achieved with attributes which
are also known as data members. The member functions determine the behavior of the class i.e.
provide a definition for supporting various operations on data held in form of an object.
Class Advantages
Classes’ just holds data and do operations with help of member variables and member
functions.
Access Modifiers
Access modifiers are used to implement important feature of Object Oriented Programming known
as Data Hiding. Consider a real life example: What happens when a driver applies
brakes? The car stops. The driver only knows that to stop the car, he needs to apply the brakes. He
is unaware of how actually the car stops. That is how the engine stops working or the internal
implementation on the engine side. This is what data hiding is.
Access modifiers or Access Specifiers in a class are used to set the accessibility of the class
members. That is, it sets some restrictions on the class members not to get directly accessed by the
outside functions.
There are 3 types of access modifiers available in C++:
1. Public
2. Private
3. Protected
Note: If we do not specify any access modifiers for the members inside the class then by default the
access modifier for the members will be Private.
Public: All the class members declared under public will be available to everyone. The data
members and member functions declared public can be accessed by other classes 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 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 are allowed to access the private data members of a
class.
Protected: Protected access modifier is similar to that of private access modifiers, the difference is
that the class member declared as Protected are inaccessible outside the class but they can be
accessed by any subclass (derived class) of that class.
Demonstrating use of private and public Data members and Member functions
#include <iostream> usingnamespace std;
class Example
{
private:
intval; public:
//function declarations voidinit_val(int v);
voidprint_val();
}; //function definitions void Example::init_val(int v)
{
val=v;
}
void Example::print_val()
{
cout<<"val: "<<val<<endl;
} int main()
{
//create object
Example Ex;
Ex.init_val(100);
Ex.print_val();
return 0;
}
It is initialized to zero when the first object of its class is created. No other initialization is
permitted.
Only one copy of that member is created for the entire class and is shared by all the objects
of that class, no matter how many objects are created.
It is visible only within the class, but its lifetime is the entire program.
Static variables are normally used to maintain values common to the entire class. For example, a
static data member can be used as a counter that records the occurrences of all the objects.
Program illustrates the use of a static data member.
#include using namespace std;
class item
{
staticint count;
int number;
public:
voidgetdata(int a)
{
number = a; count ++;
}
voidgetcount(void)
{
cout<< "Count: "; cout<< count <<"\n";
}
};
int item :: count;
int main()
{ item a,b,c;
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout<< "After reading data"<<"\n"; a.getcount();
b.getcount();
c.getcount(); return 0;
}
The output of the program would be:
Count: 0
Count: 0
Count: 0
After reading data
Count: 3
Count: 3
Count: 3
A static function can have access to only static members declared in the class.
A static member function can only have access to other static data members and functions
declared in the same class.
A static member function can be called using the class name with a scope resolution
operator instead of object name.
There can not be a static and a non-static version of the same function.
Instance
An instance is an object of a class type created via the new operator.
For example:
String *str = new String(); str is a pointer to an instance of class String. if you won`t create memory
for an object so we call that object as instance.
example: Student std; hereStudent is a class and std is a instance(means a just a copy that
class),with this we won`t do anything until unless we create a memory for that.
s
Message Passing
Objects communicate with one another by sending and receiving information to each other. A
message for an object is a request for execution of a procedure and therefore will invoke a function
in the receiving object that generates the desired results. Message passing involves specifying the
name of the object, the name of the function and the information to be sent.
Message Passing is nothing but sending and receiving of information by the objects same as people
exchange information. So this helps in building systems that simulate real life. Following are the
basic steps in message passing.
Calculate the size of an object - the size is mostly the same as that of the class but can vary.
When the object in question is not derived from a class, but from a prototype instead, the
size of an object is usually that of the internal data structure (a hash for instance) that holds
its slots.
allocation - allocating memory space with the size of an object plus the growth later, if
possible to know in advance
binding methods - this is usually either left to the class of the object, or is resolved at
dispatch time, but nevertheless it is possible that some object models bind methods at
creation time.
Object Destruction
It is generally the case that after an object is not used, it is removed from memory to make room for
other programs or objects to take that object's place. However, if there is sufficient memory or a
program has a short run time, object destruction may not occur, memory simply being deallocated at
process termination. In some cases object destruction simply consists of deallocating the memory,
particularly in garbage-collected languages, or if the "object" is actually a plain old data structure.
In other cases some work is performed prior to deallocation, particularly destroying member objects
(in manual memory management), or deleting references from the object to other objects to
decrement reference counts (in reference counting). This may be automatic, or a special destruction
method may be called on the object.
Destruction Rules
When an object is deleted, the destructors are called in the opposite order.
The rule for an object of a derived class is:
1. Call the destructor for the derived class.
2. Call the destructor for each data member object of the derived class in reverse sequence.
3. Call the destructor for the base class.
Constructor
A constructor is a special member function of the class which has the same name as that of the
class. It is automatically invoked when we declare/create new objects of the class. It is called
constructor, because it constructs the value of data members of the class.
The constructor functions have some special characteristics as follows –
1. They should be declared in the public section.
2. They are called automatically when the objects are created.
3. They do not have return types, not even void and they cannot return values.
4. They cannot be inherited, though a derived class can call the base class constructor.
5. Like other C++ functions, they can have default arguments.
6. Constructors cannot be virtual.
7. They cannot be referred by their addresses.
8. They make ‘implicit calls’ to the operators new and delete when memory allocation is required.
Syntax
class class_name {
public:
class_name()
{
// Constructor code
}
//... other Variables & Functions
}
Types Of Constructor
Default Constructor
Parameterized Constructor
Copy Constructor
Default Constructor
A default constructor does not have any parameters or if it has parameters, all the parameters have
default values.
Syntax
class class_name
{ public:
class_name(); // Default constructor with no arguments Members Declaration
}
Parameterized Constructor
If a Constructor has parameters, it is called a Parameterized Constructor. Parameterized
Constructors assist in initializing values when an object is created.
Example Program for Parameterized Constructor In C++
#include<iostream>
#include <iostream>
using namespace std;
class Employee
{ public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int i, string n, float s) //Parameterized Constructors
{ id = i; name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
} };
int main(void)
{
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee Employee
e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Copy Constructor
A copy constructor is a like a normal parameterized Constructor, but which parameter is the same
class object. Copy constructor uses to initialize an object using another object of the same class.
The copy constructor is used to −
Destructor
Destructor: it is a member function which destructs or deletes an object. The destructor function has
the same as the constructor, but it is preceded by a (tilde sign)
1. Destructors are special member functions of the class required to free the memory of the
object whenever it goes out of scope.
2. Destructors are parameter less functions.
3. Name of the Destructor should be exactly same as that of name of the class. But preceded by ‘~’
(tilde).
4. Destructor does not have any return type. Not even void.
5. The Destructor of class is automatically called when object goes out of scope.
Example
#include<iostream> usingnamespace std;
class Marks
{
public:
intmaths; int science;
Marks() //constructor
{
cout<< "Inside Constructor"<<endl;
cout<< "C++ Object created"<<endl;
}
~Marks() //Destructor
{
cout<< "Inside Destructor"<<endl;
cout<< "C++ Object destructed"<<endl;
}
};
int main( )
{
Marks m1;
Marks m2; return 0; }
Output
Inside Constructor
C++ Object created
Inside Constructor
C++ Object created
Inside Destructor
C++ Object destructed
Inside Destructor
C++ Object destructed