0% found this document useful (0 votes)
37 views14 pages

IT 304 OOPM Unit II - 1693892198

Unit ii of the Object-Oriented Programming and Methodology (OOPM) course focuses on advanced concepts that enhance the functionality and efficiency of object-oriented applications. This unit explores Exception Handling, a mechanism that ensures smooth program execution by managing runtime errors effectively using try-catch blocks, and custom exception classes. Students will learn how to handle both checked and unchecked exceptions and manage errors in complex applications.

Uploaded by

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

IT 304 OOPM Unit II - 1693892198

Unit ii of the Object-Oriented Programming and Methodology (OOPM) course focuses on advanced concepts that enhance the functionality and efficiency of object-oriented applications. This unit explores Exception Handling, a mechanism that ensures smooth program execution by managing runtime errors effectively using try-catch blocks, and custom exception classes. Students will learn how to handle both checked and unchecked exceptions and manage errors in complex applications.

Uploaded by

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

Chameli Devi Group of Institutions

Department of Information Technology

Subject Name: Object oriented programming & Methodology Subject Code: IT 304

Subject Notes

Syllabus: Object and Classes: Implementation of class and object in C++, access modifiers, object as data type,
constructor, destructor, Object as function arguments, default, copy constructor, parameterized constructor,
returning object from function, Structures vs classes, Classes objects and memory, static class data, Arrays of object,
Arrays as class Member Data, The standard C++ String class, Run time and Compile time polymorphism.

Unit-2

Object and Classes


A Class is a user defined data-type which has data members and member functions. 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. An Object is an instance of a Class.
When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is
allocated.
Implementation of class and object in C++

A class is used to specify the form of an object and it combines data representation and methods for manipulating that
data into one neat package. The data and functions within a class are called members of the class.
C++ Class Definitions
When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define
what the class name means, that is, what an object of the class will consist of and what operations can be performed on
such object.
A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of
curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined
the Box data type using the keyword class as follows −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The keyword public determines the access attributes of the members of the class that follows it. A public member can
be accessed from outside the class anywhere within the scope of the class object.
Define C++ Objects
A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class
with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two
objects of class Box −
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Both of the objects Box1 and Box2 will have their own copy of data members.

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
Chameli Devi Group of Institutions
Department of Information Technology
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 three 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.

// C++ program to demonstrate public


// access modifier
#include<iostream>
using namespace std;
// class definition
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
}
};
// main function
int main()
{
Circle obj;
// accessing public data member outside class
obj.radius = 5.5;
cout<< "Radius is:" <<obj.radius<< "\n";
cout<< "Area is:" <<obj.compute_area();
return 0;
}
Output:
Radius is: 5.5
Area is: 94.985
In the above program the data member radius is public, so we are allowed to access it outside the 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.

Example:

// C++ program to demonstrate private


// access modifier
#include<iostream>
Chameli Devi Group of Institutions
Department of Information Technology
using namespace std;
class Circle
{
// private data member
private:
double radius;
public:
void compute_area(double r)
{ // member function can access private
radius = r;
double area = 3.14*radius*radius;
cout << "Radius is: " << radius << endl;
cout << "Area is: " << area;
}
};
int main()
{
Circle obj;
// trying to access private data member
// directly outside the class
obj.compute_area(1.5);
return 0;
}
Output
Radius is: 1.5
Area is: 7.065

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.
// C++ program to demonstrate
// protected access modifier
using namespace std;
// base class
class Parent
{
// protected data members
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;
}
Chameli Devi Group of Institutions
Department of Information Technology
};
int main() {
Child obj1;
// access the protected data members of base class
obj1.setId(81);
obj1.displayId();
return 0;
}
Output:
id_protected is:81

Object as data type

When a class is defined, only the specification for the object is defined no memory or storage is allocated. To use the
data and access functions defined in the class, you need to create objects.
Syntax:
ClassName ObjectName;
Class member functions
A member function of a class is a function that has its definition or its prototype within the class definition like any other
variable.
Class access modifiers
A class member can be defined as public, private or protected. By default, members would be assumed as private.
Constructor
A class constructor is a special member function of a class that is executed whenever we create new objects of that
class. A constructor will have exact same name as the class and it does not have any return type at all, not even void.
Constructors can be very useful for setting initial values for certain member variables.
Constructor is a member function having same name as it is class, and which is used to initialize the objects of that class
type with a legal initial value. Constructor is automatically called when object is created.
Destructor
A destructor is a special member function of a class that is executed whenever an object of its class goes out of scope or
whenever the delete expression is applied to a pointer to the object of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it
take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing
files, releasing memories etc.

Objects as Function Arguments

The objects of a class can be passed as arguments to member functions as well as nonmember functions either by value
or by reference. When an object is passed by value, a copy of the actual object is created inside the function. This copy is
destroyed when the function terminates. Moreover, any changes made to the copy of the object inside the function are
not reflected in the actual object. On the other hand, in pass by reference, only a reference to that object (not the entire
object) is passed to the function. Thus, the changes made to the object within the function are also reflected in the
actual object.

Whenever an object of a class is passed to a member function of the same class, its data members can be accessed
inside the function using the object name and the dot operator. However, the data members of the calling object can be
directly accessed inside the function without using the object name and the dot operator.

To understand how objects are passed and accessed within a member function, consider this example.

Example: A program to demonstrate passing objects by value to a member function of the same class
#include<iostream.h>
Chameli Devi Group of Institutions
Department of Information Technology
class weight
{
int kilogram;
int gram;
public:
void getdata ();
void putdata ();
void sum_weight (weight,weight) ;
};
void weight::getdata()
{
cout<<"/nKilograms:";
cin>>kilogram;
cout<<"Grams:";
cin>>gram;
}
void weight :: putdata ()
{
cout<<kilogram<<" Kgs. and"<<gram<<" gros.\n";
}
void weight :: sum_weight(weight wl,weight w2)
{
gram = wl.gram + w2.gram;
kilogram=gram/1000;
gram=gram%1000;
kilogram+=wl.kilogram+w2.kilogram;
}
int main ()
{
weight wl,w2 ,w3;
cout<<"Enter weight in kilograms and grams\n";
cout<<"\n Enter weight #1" ;
wl.getdata();
cout<<" \n Enter weight #2" ;
w2.getdata();
w3.sum_weight(wl,w2);
cout<<"/n Weight #1 = ";
Chameli Devi Group of Institutions
Department of Information Technology
wl.putdata();
cout<<"Weight #2 = ";
w2.putdata();
cout<<"Total Weight = ";
w3.putdata();
return 0;
}
The output of the program is
Enter weight in kilograms and grams
Enter weight #1
Kilograms: 12
Grams: 560
Enter weight #2
Kilograms: 24
Grams: 850
Weight #1 = 12 Kgs. and 560 gms.
Weight #2 = 24 Kgs. and 850 gms.
Total Weight = 37 Kgs. and 410 gms.
In the above example, the sum_weight () function has direct access to the data members of calling object (w3 in this
case). However, the members of the objects passed as arguments (w1 and w2) can be accessed within function using the
object name and dot operator. Note that, the objects w1 and w2 are passed by value; however, they can re passed by
reference also. For example, to pass w1 and w2 by reference to the function sum_weight the function will be declared
and defined as
void sum_weight (weight &,weight &) ;
void weight :: sum_weight (weight & w1, weight &w2)
{
// body of function
}
Types of Constructor
Default Constructor-:
Default constructor is the constructor which does not take any argument. It has no parameters. Even if we do not define
any constructor explicitly, the compiler will automatically provide a default constructor implicitly.
Circle :: Circle()
{
radius = 0;
}
Parameterized Constructor -: It is possible to pass arguments to constructors. Typically these arguments help initialize
an object when it is created to create a parameterized constructor. When you define the constructor’s body, use the
parameters to initialize the object.
Example of Parameterized Constructor in C++
#include <iostream>
using namespace std;
class Point{
Chameli Devi Group of Institutions
Department of Information Technology
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1) {
x = x1;
y = y1; }
int getX() {
return x;
}
int getY(){
return y;
}
};
int main(){
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
return 0;
}
Output:
p1.x = 10, p1.y = 15

Copy Constructor-:
A copy constructor is a member function which initializes an object using another object of the same class. A copy
constructor has the following general function prototype:
ClassName (const ClassName &old_obj);
Example of copy Constructor in c++
#include<iostream>
using namespace std;
class Point{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }
// Copy constructor
Point(const Point &p1) {x = p1.x; y = p1.y; }
int getX() { return x; }
int getY() { return y; }
};
int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}
Chameli Devi Group of Institutions
Department of Information Technology
Output
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15

Returning object from function


In C++ programming, object can be returned from a function in a similar way as structures. A function can also return
objects either by value or by reference. When an object is returned by value from a function, a temporary object is
created within the function, which holds the return value. This value is further assigned to another object in the calling
function. The syntax for defining a function that returns an object by value is:

Figure 2.1: Function returing an object

To understand the concept of returning an object by value from a function, consider this example.
Example: A program to demonstrate the concept of returning objects from a function
#include<iostream.h>
class weight
{
int kilogram;
int gram;
public:
void getdata ();
void putdata ();
void sum_weight (weight,weight) ;
weight sum_weight (weight) ;
};
void weight :: getdata()
{
cout<<"/nKilograms:";
cin>>kilogram;
cout<<"Grams:";
cin>>gram;
}
void weight :: putdata ()
{
cout<<kilogram<<" Kgs. and"<<gram<<" gros.\n";
Chameli Devi Group of Institutions
Department of Information Technology
}
weight weight :: sum_weight(weight w2)
{
weight temp;
temp.gram = gram + w2.gram;
temp.kilogram=temp.gram/1000;
temp.gram=temp.gram%1000;
temp.kilogram+=kilogram+w2.kilogram;
return(temp);
}
int main ()
{
weight w1,w2 ,w3;
cout<<"Enter weight in kilograms and grams\n";
cout<<"\n Enter weight #1" ;
w3=w1.sum_weight (w2);
wl.getdata();
cout<<" \n Enter weight #2" ;
w2.getdata();
w3.sum_weight(wl,w2);
cout<<"/n Weight #1 = ";
wl.putdata();
cout<<"Weight #2 = ";
w2.putdata();
cout<<"Total Weight = ";
w3.putdata();
return 0;
}
As the return type of function is weight (an object of class weight), a temporary object temp is created within the
function for holding return values. These values are accessed as temp kilogram and temp gram by the function. When
the control returns to main (), the object temp is assigned to the object w3 in main ( ).

Structure VS Class

In C++, a structure is same as class except the following differences:

 Members of a class are private by default and members of struct are public by default.
 Classes are usually used for large amounts of data, whereas structs are usually used for smaller amounts of data.
 Classes can be inherited whereas structures not.
 A structure couldn't be null like a class.
 A structure couldn't have a destructor such as a class.
 A structure can't be abstract, a class can.
 Declared events within a class are automatically locked and then they are thread safe, in contrast to the
structure type where events can't be locked.
Classes objects and memory:

Before using a member of a class, it is necessary to allocate the required memory space to that member. The way the
memory space for data members and member functions is allocated is different regardless of the fact that both data
members and member functions belong to the same class.
Chameli Devi Group of Institutions
Department of Information Technology
The memory space is allocated to the data members of a class only when an object of the class is declared, and not
when the data members are declared inside the class. Since a single data member can have different values for different
objects at the same time, every object declared for the class has an individual copy of all the data members.

On the other hand, the memory space for the member functions is allocated only once when the class is defined. In
other words, there is only a single copy of each member function, which is shared among all the objects. For instance,
the three objects, namely, book1, book2 and book3 of the class book have individual copies of the data members title
and price. However, there is only one copy of the member functions getdata () and putdata () that is shared by all the
three objects

Static class data (Static Data Members of the class)

We can define class member’s static using static keyword. When we declare a member of a class as static it means no
matter how many objects of the class are created, there is only one copy of the static member.

A static member is shared by all objects of the 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 as done in
the following example by declaring the static variable, using the scope resolution operator (::) to identify which class it
belongs to.

Example to understand the concept of static data members:


#include <iostream>
using namespace std;
class Box {
public:
static int objectCount;
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout<<"Constructor called." <<endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume() {
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Initialize static member of class Box
int Box::objectCount = 0;
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2

// Print total number of objects.


cout<< "Total objects: " << Box::objectCount<<endl;
return 0;
Chameli Devi Group of Institutions
Department of Information Technology
}
Static Function Members

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.

Array of Objects

 Like array of other user-defined data types, an array of type class can also be created.
 The array of type class contains the objects of the class as its individual elements.
 Thus, an array of a class type is also known as an array of objects.
 An array of objects is declared in the same way as an array of any built-in data type.
Syntax:

class_name array_name [size];


Example:
#include <iostream>
class MyClass {
int x;
public:
void setX(int i) { x = i; }
int getX() { return x; }
};
void main()
{
MyClass obs[4];
int i;
for(i=0; i < 4; i++)
obs[i].setX(i);
for(i=0; i < 4; i++)
cout << "obs[" << i << "].getX(): " << obs[i].getX() << "\n";
getch();
}
Output:
obs[0].getX(): 0
obs[1].getX(): 1
obs[2].getX(): 2
obs[3].getX(): 3
Arrays as class Member Data
Arrays can be declared as the members of a class. The arrays can be declared as private, public or protected members of
the class.
Example: A program to demonstrate the concept of arrays as class members
#include<iostream>
using namespace std;
const int size=5;
class student
{
int roll_no;
int marks[size];
public:
Chameli Devi Group of Institutions
Department of Information Technology
oidtot_marks ();
voidgetdata ();
v} ;
void student :: getdata ()
{
cout<<"\nEnter roll no: ";
cin>>roll_no;
for(int i=0; i<size; i++)
{
cout<<"Enter marks in subject"<<(i+1)<<": ";
cin>>marks[i] ;
}
void student :: tot_marks() //calculating total marks
{
int total=0;
for(int i=0; i<size; i++)
total+ = marks[i];
cout<<"\n\nTotal marks "<<total;
}
int main(){
student stu;
stu.getdata() ;
stu.tot_marks() ;
return 0;
}
Standard C++ String class

Strings are objects that repr esent sequences of characters. The standard string class provides support for such objects
with an interface similar to that of a standard container of bytes, but adding features specifically designed to operate
with strings of single-byte characters. This class is called std:: string. String class stores the characters as a sequence of
bytes with a functionality of allowing access to single byte character.
std:: string vs Character Array
 A character array is simply an array of characters can terminate by a null character. A string is a class which
defines objects that be represented as stream of characters.
 Size of the character array has to allocate statically; more memory cannot be allocated at run time if required.
Unused allocated memory is wasted in case of character array. In case of strings, memory is allocated dynamically.
More memory can be allocated at run time on demand. As no memory is preallocated, no memory is wasted.
 There is a threat of array decay in case of character array. As strings are represented as objects, no array
decay occurs.
 Implementation of character array is faster than std:: string. Strings are slower when compared to
implementation than character array.
 Character array do not offer much inbuilt functions to manipulate strings. String class defines a number of
functionalities which allow manifold operations on strings.
Operations on strings
Input Functions

1. getline() :- This function is used to store a stream of characters as entered by the user in the object memory.

2. push_back() :- This function is used to input a character at the end of the string.

3. pop_back() :- This function is used to delete the last character from the string.
Chameli Devi Group of Institutions
Department of Information Technology
// C++ code to demonstrate the working of
// getline(), push_back() and pop_back()
#include<iostream>
#include<string> // for string class
using namespace std;
int main()
{
// Declaring string
string str;
// Taking string input using getline()
getline(cin,str);
// Displaying string
cout << "The initial string is : ";
cout << str << endl;
str.push_back('s');
cout << "The string after push_back operation is : ";
cout << str << endl;
str.pop_back();
cout << "The string after pop_back operation is : ";
cout << str << endl;
return 0;

Run time and Compile time polymorphism

Polymorphism means “multiple” + “Forms”. It is one feature of Object-Oriented Paradigm having ability of taking more
than one form. Polymorphism is a feature of OOPs that allows the object to behave differently in different conditions.

In C++ we have two types of polymorphism:

1) Compile time Polymorphism – This is also known as static (or early) binding.
2) Runtime Polymorphism – This is also known as dynamic (or late) binding.

1) Compile time Polymorphism


Function overloading and Operator overloading are perfect example of Compile time polymorphism.

Compile time Polymorphism Example


In the below example, we have two functions with same name but different number of arguments. Based on how many
parameters we pass during function call determines which function is to be called, therefore it is considered as an
example of polymorphism because in different conditions the output is different. Since, the call is determined during
compile time that’s why it is called compile time polymorphism.

#include <iostream>
using namespace std;
class Add {
public:
int sum(int num1, int num2){
return num1+num2;
}
int sum(int num1, int num2, int num3){
return num1+num2+num3;
Chameli Devi Group of Institutions
Department of Information Technology
}
};
int main() {
Add obj;
cout<<"Output: "<<obj.sum(10, 20)<<endl;
cout<<"Output: "<<obj.sum(11, 22, 33);
return 0;
}
Output:
Output: 30
Output: 66
2) Runtime Polymorphism
Function overriding is an example of Runtime polymorphism.
Function Overriding: When child class declares a method, which is already present in the parent class then this is called
function overriding, here child class overrides the parent class. In case of function overriding we have two definitions of
the same function; one is parent class and one in child class. The call to the function is determined at runtime to decide
which definition of the function is to be called, that’s the reason it is called runtime polymorphism.
Example of Runtime Polymorphism
#include <iostream>
using namespace std;
class A {
public:
void disp(){
cout<<"Super Class Function"<<endl;
}
};
class B: public A{
public:
void disp(){
cout<<"Sub Class Function";
}
};
int main() {
//Parent class object
A obj;
obj.disp();
//Child class object
B obj2;
obj2.disp();
return 0;
}
Output:
Super Class Function
Sub Class Function

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy