Professional Documents
Culture Documents
Ratio(int i)
{
cout << "conversion from basic(int)
to user defined data type occured"
<< endl;
num = i;
den = i;
}
• Conversion from user-defined type of basic data type is done by overloading the cast operator
of basic type as a member function.
• Operator function is defined as an overloaded basic data type which takes no arguments.
• Return type of operator is not specified because the cast operator function itself specifies the
return type.
class class_name {
...
public:
operator data_type() {
//Conversion code
}
};
int main()
{
operator int() Ratio rr(4,5); int numerator;
{ numerator = rr;
return num; rr.Display();
} cout << "Numerator: " << numerator;
}
• For bar to be initialized, the function-scoped foo has to be copied from the function’s stack frame into the outer-
scoped bar variable, an expensive copy. What if there was a way for bar to just become the function-scoped foo
(i.e. whenever foo is used, just use bar instead?).
• Remember that the return value of BuildBigObject is a temporary rvalue. It will disappear when
BuildBigObject's stack frame is popped. The compiler can detect that foo is a temporary and instead of
discarding it, it will make bar and foo refer to the same memory location in the invocation of BuildBigObject.
That means that when BuildBigOjbect is initializing foo, it is actually doing work on the outer-scoped bar.
int nValue;
float fValue;
void *ptr;
ptr = &nValue; // valid
ptr = &fValue; // valid
//cout << *voidPtr << endl; // illegal: cannot dereference a void pointer
cout << *intPtr << endl; // then we can dereference it like normal
private:
int custNum;
double balanceDue;
void displayCustomer(); function "Customer::displayCustomer" is inaccessible
friend void displayAsAFriend(Customer);
public:
Customer(int = 0, double = 0.0);
};
Object oriented programming in C++ by Robert Lafore 22
Contd..
• Member functions will have the access on its own private variables and some
public variables of other classes but a friend function will have the accessibility on
private variable of other classes too.
class beta; //needed for frifunc class beta
declaration {
private: int main()
class alpha
int data; {
{
public: alpha aa;
private:
beta() : data(7) { } beta bb;
int data;
friend int frifunc(alpha, beta); //friend function cout << frifunc(aa, bb) << endl;
public:
}; return 0;
alpha() : data(3) { }
int frifunc(alpha a, beta b) //function definition }
friend int frifunc(alpha, beta); //friend
function {
}; return( a.data + b.data );
}