Lecture 05 OOP
Lecture 05 OOP
(OOP)
Lecture 05
CONTENT
Constructors: Example Problems
Problem#1
Problem#2
Problem#3
Problem#4
Problem#5
3
Name (string)
Age (int)
Grade (char)
The class should have a default constructor that initializes these data members with default values:
Name: "Unknown"
Age: 0
Grade: 'U'
1. Default Constructor: This initializes the name as "Unknown", age as 0, and grade as 'U'.
2. setDetails Function: This allows setting the values for name, age, and grade.
1. student1 uses the default constructor, so its details are initialized to default values.
2. student2 has its details set explicitly using the setDetails function.
Write a program to define a class Rectangle with the following data members:
Length (float)
Breadth (float)
The class should have a parameterized constructor that initializes the length and breadth.
Also, write a member function area() to calculate the area of the rectangle.
In main(), create two objects using the parameterized constructor with different values and
print their areas.
8
public: cout << "Area of rect1: " << rect1.area() << endl;
// Parameterized constructor cout << "Area of rect2: " << rect2.area() << endl;
Rectangle(float l, float b) {
length = l;
breadth = b; }
return 0;
// Function to calculate area }
float area() {
return length * breadth; } };
9
Width (float)
Height (float)
Depth (float)
A parameterized constructor that takes three arguments and initializes the width, height, and depth.
A constructor with one parameter that initializes a cube (all sides equal).
In main(), create three different objects using the different constructors, and write a function to calculate the volume of
the box. Display the volume of each box.
12
// Parameterized constructor
Box(float w, float h, float d) { cout << "Volume of box1: " << box1.volume() << endl;
width = w; cout << "Volume of box2: " << box2.volume() << endl;
height = h;
depth = d; } cout << "Volume of box3 (cube): " << box3.volume() <<
endl;
// Constructor for cube
Box(float side) {
return 0;
width = height = depth = side; }
}
13
Volume of box1: 1
Volume of box2: 30
Volume of box3 (cube): 27
14
Title (string)
Author (string)
Price (float)
In main(), create one object using the parameterized constructor and another using the copy constructor.
Write a program that defines a class Account with the following attributes:
Balance (float)
The class should have a parameterized constructor with default arguments. If the account holder's name is not provided, it should be
initialized to "Unknown", and the balance should default to 0.
Display the account details for each object using a member function.
20