Home > Software engineering >  how to add two private data of same class in c ?
how to add two private data of same class in c ?

Time:12-07

If we have two private varaibles of same class i.e x and y. Then we initizalize its value as 5 and 4. Then how can we add both of them.

// Online C   compiler to run C   program online
#include <iostream>
using namespace std;
class pukar{
    int x,y;
    public:
   

    void setdata(int x1){
        x=x1;
        friend void add(pukar);
    }
    void setdata1(int y1){
        y=y1;
    }
    friend void add(pukar);
};
void add(pukar o1){
    
   cout<<"The sum is "<<o1.x o1.y<<endl;
}

int main() {
    pukar rimal;
    rimal.setdata(5);
    rimal.setdata1(3);
    rimal.add();
 
    return 0;
}

I tried this code but it is throwing errors.

CodePudding user response:

You have three issues.

  • Unexpected friend function declaration inside pukar::setdata. This is unnecessary and can be removed.
  • add accesses an undeclared o2. This should likely be cout<<"The sum is "<<o1.x o1.y<<endl;
  • You call add as a member function of pukar rather than a standalone function. Try add(rimal); instead.

While your code will work with using namespace std; it is discouraged. Rather either fully wualify your names with std:: or use using scoped locally.

void add(pukar o1) {
   using std::cout;
   using std::endl;

   cout << "The sum is " << o1.x   o2.y << endl;
}

CodePudding user response:

Remove friend line here

void setdata(int x1){
    x=x1;
    friend void add(pukar); // <--- delete this line
}

friend can only be used at the top level within a class.

Change o2 to o1 here

void add(pukar o1){
    
   cout<<"The sum is "<<o1.x o2.y<<endl;
}

Here o2 is an undeclared variable.

Change this

rimal.add();

to this

add(rimal);

add is a global function, it is not a member of the pukar class. It's a friend of the pukar class but that does not make it a member of the class.

  • Related