Passing Arguments And Returning
Objects are passed to functions by-value, as is standard in C++.
When an object is passed to a function, a copy of it is created. The constructor
called for an object being passed to a function is the copy constructor.
The copy constructor, unless specified, creates an identical copy of the object
passed as an argument. When an object is destroyed, the destructor is always
called.
Example
#include <iostream>
using namespace std;
class intClass // creates a new class
{
int a; // by definition all members of a class are
// private: not accessible from outside the class
public:
void seta(int x) // members preceded by public: can
// be accessed from the outside
{
a = x; // a, although private, can be accessed by
// seta() because seta() is a member of intClass
}
int geta()
{
return a;
}
};
intClass doubleValue(intClass y) // takes and object intClass as
// a parameter and returns an intClass
{
y.seta(y.geta() * 2); // here y is not the original argument but a
// copy of it. The constructor called for this copy is the copy constructor,
// which in this case coincides with the standard constructor
return y;
}
int main()
{
intClass obj1;
intClass obj2;
obj1.seta(10);
cout << "obj1\'s a is: " << obj1.geta() << endl;
obj2 = doubleValue(obj1);
cout << "obj2\'s a is: " << obj2.geta() << endl;
}
Output
obj1's a is: 10
obj2's a is: 20