1) Create a simple C++ program to instantiate an object that will store two numb
ID: 3882001 • Letter: 1
Question
1) Create a simple C++ program to instantiate an object that will store two numbers and perform mathematical operations using those numbers as operands. The class should have a header called Adder.h and a .cpp file called Adder.cpp. Testing should be done in a separate .cpp file called main.cpp. The class should have at least two constructors. The default constructor should instantiate both operands to 2. A second constructor should accept two numbers as arguments and use the arguments to set the local operands. The class should have 6 functions: add(), subtract(), multiply(), divide(), get(), and set(). The first four functions should return the result of performing the stated operations using the two operands and take no arguments. Get() should take one argument to specify which operand to return. Set() should take two arguments, the first to specify which operand to set and the second to specify the number to set the operand equal to. Your code should document each function, and the class, with comments.
Explanation / Answer
Adder.h
#ifndef ADDER_H
#define ADDER_H
class Adder // class definition with function declarations
{
private :
int first,second; // private variable
public:
Adder(int a,int b); // parametrized constructor
int add(); // function declarations
int subtract(); // function declarations
int multiply(); // function declarations
int divide(); // function declarations
int get(char s[] ); // function declarations
void set(char s[],int); // function declarations
};
#endif
Adder.cpp
#include<iostream>
#include<string.h>
#include"Adder.h"
using namespace std;
Adder :: Adder() : first(2),second(2) // defualt constructor
{
}
Adder :: Adder(int a,int b) : first(a),second(b) // parametrized constructor
{
}
int Adder :: add() // add() function
{
return first+second;
}
int Adder :: subtract() // subtract() function
{
return first-second;
}
int Adder::multiply() // multiply() function
{
return first*second;
}
int Adder::divide() // divide() function
{
return first/second;
}
int Adder::get(char s[]) // get() function
{
if(strcmp(s,"first"))
return first;
if(strcmp(s,"second"))
return second;
}
void Adder::set(char s[],int value) // set() function
{
if(strcmp(s,"first"))
first=value;
if(strcmp(s,"second"))
second=value;
}
main.cpp
#include<iostream>
#include "Adder.h"
using namespace std;
int main()
{
Adder obj(22,55); // making object and passing to parametrized constructor
cout<<"Addition is : "<<obj.add()<<endl;
cout<<"Subtraction is : "<<obj.subtract()<<endl;
cout<<"Multiplication is : "<<obj.multiply()<<endl;
cout<<"Division is : "<<obj.divide()<<endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.