Object-Oriented Concepts Through CPP
Friend Function and Friend Class
(10 Marks)
Objectives:
- To understand the concept of a friend function and friend class in C++.
- To learn how to declare and define friend functions and friend classes in C++.
- To understand the difference between a friend function and a member function in C++.
- To learn how to use a friend function and friend class in C++ programs.
Instructions:
- This assignment consists of both theoretical and practical questions.
- Answer all questions in a clear and concise manner.
- Submit your answers in a document format.
- Be sure to include proper formatting, grammar, and spelling.
- All code snippets must be properly formatted and commented.
Part 1: Theoretical Questions
Question 1: What is a friend function in C++? How is it different from a member function? Provide an example to illustrate the difference.
Question 2: When should you use a friend function or friend class in C++? Provide examples.
Part 2: Practical Questions
Question 3: Write a C++ program that demonstrates the use of a friend function. Define a class named Rectangle with two private data members' length and width. Implement a friend function named findArea() that calculates and returns the area of the rectangle.
Question 4: Write a C++ program that demonstrates the use of a friend class. Define a class named BankAccount with two private data members balance and interestRate. Implement a friend class named Bank with a function named getInterest() that calculates and returns the interest on the bank account using the interest rate.
Question 5: Write a C++ program that demonstrates the use of both a friend function and friend class. Define a class named Date with three private data members day, month, and year. Implement a friend function named isLeapYear() that determines whether a given year is a leap year or not. Implement a friend class named DateOperations with functions named incrementDay() and incrementMonth() that increment the day and month of the date object, respectively.
Part 3: Code Review
Question 6: Review the following code snippet and identify any errors or issues:
class Rectangle { private: double length; double width; public: Rectangle(double l, double w) { length = l; width = w; } friend double findPerimeter() { return 2 * (length + width); } }; int main() { Rectangle r(5, 10); double perimeter = r.findPerimeter(); cout << "Perimeter: " << perimeter << endl; return 0; }
Submission Guidelines:
- Submit the document containing all answers to the questions.
- Ensure the document is properly formatted and all code snippets are properly commented on.
- Submit your assignment before the deadline 24 April 2023.
No comments:
Post a Comment