Experiment 1
Aim
To design and implement C++ classes using static members,
methods with default arguments, and friend functions, including
matrix-vector multiplication using a friend function.
Objectives
- To
understand static data members and static member functions.
- To
implement default arguments in member functions.
- To
understand and implement friend functions.
- To
perform matrix-vector multiplication using classes.
Theory
A static data member is shared by all objects of a
class and has only one copy. A static member function can be called
using the class name. A default argument allows a function to use a
predefined value when an argument is not supplied. A friend function is
a non-member function that can access the private and protected members of a
class.
Algorithm
- Define
a Matrix class with a static object counter.
- Define
a Vector class with a constructor having default arguments.
- Declare
a friend function for Matrix-Vector multiplication.
- Accept
matrix elements and vector values.
- Perform
matrix-vector multiplication through the friend function.
- Display
the result and number of Matrix objects created.
Program
#include <iostream>
using namespace std;
class Vector;
class Matrix {
int a[2][2];
static int count;
public:
Matrix() {
count++;
cout <<
"Enter 2x2 matrix:\n";
for (int i =
0; i < 2; i++)
for (int j
= 0; j < 2; j++)
cin
>> a[i][j];
}
static void
showCount() {
cout <<
"Matrix objects: " << count << endl;
}
friend void
multiply(Matrix, Vector);
};
int Matrix::count = 0;
class Vector {
int v[2];
public:
Vector(int x = 1,
int y = 1) {
v[0] = x;
v[1] = y;
}
friend void
multiply(Matrix, Vector);
};
void multiply(Matrix m, Vector v) {
cout <<
"Matrix-Vector Product:\n";
for (int i = 0; i
< 2; i++)
cout <<
m.a[i][0] * v.v[0] +
m.a[i][1] * v.v[1] << endl;
}
int main() {
Matrix m;
Vector v;
multiply(m, v);
Matrix::showCount();
return 0;
}
Sample Output
Enter 2x2 matrix:
1 2
3 4
Matrix-Vector Product:
3
7
Matrix objects: 1
Result
Thus, C++ classes were successfully implemented using static
members, default arguments and a friend function for matrix-vector
multiplication.
Viva Questions
- What
is a static data member?
- How
is a static member initialized?
- What
is a default argument?
- What
is a friend function?
- Can
a friend function be called using an object?
- Why
is a friend function used in this program?
No comments:
Post a Comment