February 29, 2012

Multiplication of objects, array based objects, object multiply by object

#include <cstdlib>
#include <iostream>

using namespace std;

//Objectmultiplication class declaration
class Objectmultiplication
{
private:
int array_integers[10]; //Array declaration

public:

//A default constructor which will initialize all array elements with zero
Objectmultiplication()
{
array_integers[0]=0;
array_integers[1]=0;
array_integers[2]=0;
array_integers[3]=0;
array_integers[4]=0;
array_integers[5]=0;
array_integers[6]=0;
array_integers[7]=0;
array_integers[8]=0;
array_integers[9]=0;
}

//Declaration of setter and getter functions

void setArray1();
void setArray2();
void getArray();

//An operator overloading function which will overload * operator for this class

Objectmultiplication operator*(Objectmultiplication);

};

Objectmultiplication Objectmultiplication::operator *(Objectmultiplication secondobject)
{
Objectmultiplication multi;

int val=0;

//Multiplying both objects and storing the result of multiplication in third object

while(val<=10)
{
multi.array_integers[val] = array_integers[val]*secondobject.array_integers[val];
val++;
}

return(multi);
}

void Objectmultiplication::setArray1(void)
{
//Using hard coded values, for first object
int val;
for(val=0; val<10; val++)
{
array_integers[val] = (val+1);
}
}

void Objectmultiplication::setArray2(void)
{
//Using hard coded values, for second object
int val=10, indexes;

for(indexes=0; indexes<10; indexes++)
{
array_integers[indexes] = val;
val–;
}
}

void Objectmultiplication::getArray(void)
{
int val;

for(val=0; val<10; val++)
cout << array_integers[val] << ” \n”;
}

int main()
{
//You are required to create three objects of the same class
Objectmultiplication obj1;
Objectmultiplication obj2;
Objectmultiplication obj3;

//Assigning values to first and second objects through setter functions.
//Using hard coded values.
obj1.setArray1();

obj2.setArray2();

//Multiplying both objects and storing the result of multiplication in third object
//Our program is supporting the statement like a = b * c
//where a, b and c are objects of the same class

obj3 = obj1*obj2;

//Displaying the values of first and second object through getter functions
cout << “Object 1 : \n”;
obj1.getArray();

cout << “\n”;
cout << “Object 2 : \n”;
obj2.getArray();

cout << “\n”;
cout << “Multiplication of both objects : \n”;
obj3.getArray();

system(“PAUSE”);
return EXIT_SUCCESS;

}

Last updated: March 19, 2014