Presentation is loading. Please wait.

Presentation is loading. Please wait.

Function Overloading Can enables several function Of same name Of different sets of parameters (at least as far as their types are concerned) Used to create.

Similar presentations


Presentation on theme: "Function Overloading Can enables several function Of same name Of different sets of parameters (at least as far as their types are concerned) Used to create."— Presentation transcript:

1 Function Overloading Can enables several function Of same name Of different sets of parameters (at least as far as their types are concerned) Used to create several functions of the same name that perform similar tasks but on different data types

2 Square function int square(int x) { return x*x; } double square(double y) { return y*y;} float square(float z) { return z*z;}

3 Use overloaded function Complier will search for the match function prototype int main() { int x=7; double y=7.5; cout<<“square of “<<x<<“ is “ <<square(x)<<endl; cout<<“Square of “<<y<<“is “ <<square(y)<<endl; }

4 Friend function and friend class A friend function of a class is defined outside that class scope Has right to access private members of the class Using friend functions can enhance performance Often appropriate when a member function cannot be used for certain operations

5 Declare a function as friend To declare a function as a friend of a class, precede the function prototype in class definition with key word friend To declare a class Two as a friend of One, place friend class Two; in the definition of class One

6 Friendship Friendship is granted, not taken Friendship is not symmetric If B is friend of A, I.e. A declared B as friend, you cannot infer A is friend of B unless B declare A as friend Friendship is not transitive A is friend of B, and B is friend of C, you cannot say that A is friend of C

7 Example class Count { friend void setX(Count &, int); public: Count(){x=0;} void print() const {cout<<x<<endl;} private: int x; };

8 Example continue void setX(Count &c, int val) { c.x = val; } int main() { Count counter; counter.print(); setX(counter, 8); return 0; }

9 Use this pointer Every object has access to its own address through a pointer called this This pointer is not part of object This pointer is passed into object (by compiler) as implicit first argument on every non-static member function

10 class Test { int x; public: Test( int =0); void print() const; }; Test::test(int a){ x = a;} void Test::print() const { cout<<“ x = “<<x x = “ x <<“\n(*this).x = “<<(*this).x <<endl; }

11 int main() { Test t(12); t.print(); return 0; } x = 12 this->x = 12 (*this).x = 12 Output:


Download ppt "Function Overloading Can enables several function Of same name Of different sets of parameters (at least as far as their types are concerned) Used to create."

Similar presentations


Ads by Google