unit3
unit3
Course Content
• Object & Classes,
• Scope Resolution Operator,
• Constructors
• Destructors
• Friend Functions
• Inheritance,
• Polymorphism
• Overloading Functions & Operators
• Types of Inheritance
• Virtual functions.
• Introduction to Data Structures.
Prof. Mahima Jain
Asst. Professor
(CSE)
BASIC PRINCIPLES OF OOP
Object :
•An Object is an identifiable entity with some characteristics
and behaviour. 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.
•To use the data and access functions defined in the class,
you need to create objects.
class person
{ char name[20];
int id;
public:
void getdetails(){}
};
int main()
{
person p1; // p1 is a object
}
};
• Constructors are automatically called even when not
declared, at that time default constructors are called.
Default contractors are destroyed as soon as we declare
constructor.
• Copy constructors
• Parameterized constructors
• Default Constructors
class class_name
{
};
Program
#include <iostream>
using namespace std;
class Rectangle {
private:
int length;
int width;
public:
Rectangle(int l, int w) {
length=l;
width=w;
} friend int calculateArea(Rectangle rect); // Friend function declaration
};
// Friend function definition
int calculateArea(Rectangle rect) {
return rect.length * rect.width;
}
int main() {
Rectangle rect(10, 5);
cout << "Area of the rectangle: " << calculateArea(rect) << endl;
return 0;
}
Inheritance
// Area of a circle
// Function to calculate the area of a circle
cout << "Enter the radius of the circle: ";
double area(double radius) {
return 3.14159 * radius * radius; cin >> radius;
} cout << "Area of the circle: " <<
area(radius) << endl;
// Function to calculate the area of a rectangle
double area(double length, double width) { // Area of a rectangle
return length * width; cout << "Enter the length and width of the
} rectangle: ";
cin >> length >> width;
cout << "Area of the rectangle: " <<
area(length, width) << endl;
return 0;
}
• Operating Overloading:C++ also provide option to
overload operators. For example, we can make the
operator (‘+’) for string class to concatenate two strings.
We know that this is the addition operator whose task is
to add two operands. So a single operator ‘+’ when
placed between integer operands , adds them and when
placed between string operands, concatenates them.