35.3k views
1 vote
Given ProblemSolution class. Use a pointer to object of "ProblemSolution" class to invoke the "CalculateSum" and "Print" methods of "ProblemSolution".

Write a function:
void Solution(int N1, int N2)

that accepts two integers N1 and N2. The function should instantiate "ProblemSolution" object with N1 and N2 values and call "CalculateSum" and "Print" method by creating a pointer to the object of "ProblemSolution".

Input
12 5

Output
17
Assume that,

N1, N2 and sum are integers within the range [-1,000,000,000 to 1,000,000,000].
Given Code to work with:

#include
#include
#include
using namespace std;

class ProblemSolution{
int N1,N2,result;
public:
ProblemSolution(int N1, int N2){

1 Answer

2 votes

Answer:

#include <iostream>

using namespace std;

class ProblemSolution {

private:

int num1, num2;

public:

ProblemSolution(int n1, int n2) {

num1 = n1;

num2 = n2;

}

int calculateSum() {

int sum = 0;

sum = num1 + num2;

return sum;

}

void printSum() {

// calculateSum will return sum value that will be printed here

cout <<"Sum = "<< calculateSum();

}

~ProblemSolution() {

cout << "\\Destructor is called " << endl;

};

};

int main() {

int a, b;

cout << "Enter a: ";

cin >> a;

cout << "Enter b: ";

cin >> b;

// Initiallizing object pointer of type ProblemSolution

ProblemSolution *objPtr = new ProblemSolution(a,b);

// printing Sum

objPtr->printSum();

// delete objPtr to relaease heap memory :important

delete objPtr;

return 0;

}

Step-by-step explanation:

we will initialize a pointer "objPtr" and initallize the constructor by passing 2 values a and b followed by the keyword "new". the keyword "new" allocates memory in the heap. we can access class member functions using arrow "->". it is important to delete objPtr at the end of the program so that the heap memory can be freed to avoid memory leakage problems.

User Erich Neuwirth
by
5.4k points