Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Monday, August 17, 2026

To design and implement C++ classes using static members, methods with default arguments, and friend functions, including matrix-vector multiplication using a friend function.

 

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

  1. Define a Matrix class with a static object counter.
  2. Define a Vector class with a constructor having default arguments.
  3. Declare a friend function for Matrix-Vector multiplication.
  4. Accept matrix elements and vector values.
  5. Perform matrix-vector multiplication through the friend function.
  6. 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

  1. What is a static data member?
  2. How is a static member initialized?
  3. What is a default argument?
  4. What is a friend function?
  5. Can a friend function be called using an object?
  6. Why is a friend function used in this program?

No comments:

Post a Comment