C++ Class Definition Implementing add()
, subtract()
and multiply()
for Integer class
#include <iostream> class Integer/* www . j a v a 2 s. c o m*/ { private: int n; public: Integer(int m = 0); Integer(Integer& obj); // Copy constructor int compare(const Integer& obj) const; // Compare function with reference paramter int getValue() {return n;} void setValue(int m){ n = m; } void show(); Integer* add(const Integer& obj); Integer* add(int m); Integer* subtract(const Integer& obj); Integer* subtract(int m); Integer* multiply(const Integer& obj); Integer* multiply(int m); }; using std::endl; // Copy constructor Integer::Integer(Integer& obj) : n(obj.n) { std::cout << "Object created by copy constructor." << std::endl; } // Constructor Integer::Integer(int m) : n(m) { std::cout << "Object created." << std::endl; } Integer* Integer::add(const Integer& obj) { n += obj.n; return this; } Integer* Integer::subtract(const Integer& obj) { n -= obj.n; return this; } Integer* Integer::multiply(const Integer& obj) { n *= obj.n; return this; } void Integer::show() { std::cout << "Value is " << n << std::endl; } // Compare function with reference parameter int Integer::compare(const Integer& obj) const { if(n < obj.n) return -1; else if(n==obj.n) return 0; return 1; } int main() { Integer a {4}; Integer b {6}; Integer c {7}; Integer d {8}; Integer x {5}; Integer result {a}; // Set result object as copy of a Integer* pResult = &result; std::cout << "Result is " << pResult->multiply(x)->add(b)->multiply(x)->add(c)->multiply(x)->add(d)->getValue() << std::endl; }