Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++: Write a class having two private integer variables, one constructor that wi

ID: 3783281 • Letter: C

Question

C++:

Write a class having two private integer variables, one constructor that will initialize the variables, one member function which will handle the private integer variables, and the other member function which will return the result of the addition of the variables.

a. Declare a class variable and display the result of member function after saving values to the integer variables.

b. Declare a pointer class variable that will take the address of the class variable declared in (a) and replace values of the integer variables using the pointer class variable.

Explanation / Answer

#include <iostream>
using namespace std;

class Class
{
   private:
   int a,b;         //private integer variables
  
   public:
   Class(int a,int b)   //constructor to initialize variables
   {
       this->a = a;
       this->b = b;
      
   }
   void setab(int a,int b)
   {
       this->a = a;
       this->b = b;
   }
   int sum()             //function to return the sum of variables
   {
       return a+b;
   }
};
int main()
{
   Class c(34,54);   //object c of class Class initializing the values of a and b
   cout<<" Sum of a and b by object c : "<<c.sum();   //call sum() method
  
   Class *ptr = &c;
  
   ptr->setab(67,98);
   cout<<" Sum of and b set by ptr : "<< c.sum();   //call sum() method again
  
  
  
   return 0;
}

output:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote