I have not used an object to call the function but have passed objects as parameters and call function without an object. Can anyone explain

#include <iostream>
using namespace std;
class test
{  int a;
  public:
  test(int x): a(x) {}
  void display()
  {
    cout<<"the value of a is"<<a<<endl;
   }
   void swap(test &t, test &t1)
   {
     test tmp( t1 );
    t1 = t;
    t = tmp;
    }
   };
   int main()
   {
     test t(20), t1(30);
     swap(t,t1);
     t.display();
     t1.display();
    return 0;
    }

See the slight revisions and the comments added ...

#include <iostream>

using namespace std;

class Test
{
public:
    Test(int x): a(x) {} // constructor //
    void display()
    {
        cout << "The value of a is: " << a << endl;
    }
private:
    int a;
    friend void swap( Test& t, Test& t1 );
} ;

// passed in by reference so that (addresses to) objects
// in the calling scope are passed in, 
// (and not local copies used inside) //
void swap( Test& t, Test& t1 ) 
{
    Test tmp( t1 ); // make a tmp copy of t1
    t1 = t; // set t1 (value) to t (value)
    t = tmp; // tmp was holding original value of t1, so assign to t //
}


int main()
{
    Test t(20), t1(30); // construct t to hold 20 and t1 to hold 30
    swap(t, t1); // after this call t holds 30 and t1 holds 20
    t.display(); // prints: The value of a is: 30 
    t1.display(); //on NEXT line prints: The value of a is: 20 
    return 0; // returns 0 value to indicate successful program run //
}

Edited 9 Months Ago by David W

This article has been dead for over six months. Start a new discussion instead.