Computer Notes - Friend Functions

download Computer Notes - Friend Functions

of 34

Transcript of Computer Notes - Friend Functions

  • 8/3/2019 Computer Notes - Friend Functions

    1/34

    Friend FunctionsFriend Functions

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    2/34

    CompositionCompositionConceptual notation:Conceptual notation:

    String()

    SetString(char *) : void

    GetString() const : const char *

    ~String()

    gpa : float

    rollNo : int

    name : String

    Student(char * = NULL, int = 0,

    float = 0.0);

    Student(const Student &)

    GetName() const : String

    GetNamePtr() const : const char *

    SetName(char *) : void~Student()

    Student

    string : char *

    String

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    3/34

    CompositionComposition

    Main Function:Main Function:

    intintmain(){main(){StudentStudent aStudent("FakhiraStudent("Fakhir", 899,", 899,

    3.1);3.1);coutcout

  • 8/3/2019 Computer Notes - Friend Functions

    4/34

    CompositionCompositionOutput:Output:

    Constructor::StringConstructor::String....

    Constructor::StudentConstructor::Student....

    Name:Name: FakhirFakhir

    Destructor::StudentDestructor::Student....Destructor::StringDestructor::String....

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    5/34

    CompositionCompositionStudent::Student(charStudent::Student(char * n,* n,

    intint roll, float g){roll, float g){

    coutcout

  • 8/3/2019 Computer Notes - Friend Functions

    6/34

    CompositionCompositionTo assign meaningful values to the object,To assign meaningful values to the object,

    the functionthe function SetStringSetString is called explicitly inis called explicitly inthe constructorthe constructor

    This is an overheadThis is an overhead

    SubSub--objectobject namename in thein the studentstudent class canclass can

    be initialized using the constructorbe initialized using the constructor

    Member initialization listMember initialization listsyntax is usedsyntax is used

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    7/34

    CompositionCompositionAdd an overloaded constructor to theAdd an overloaded constructor to the

    StringString class defined above:class defined above:

    class String{class String{char *char *ptrptr;;

    public:public:String();String();

    String(charString(char *);*);String(constString(const String &);String &);

    voidvoidSetName(charSetName(char *);*);~String();~String();

    };};

    //String(char * = NULL);

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    8/34

    CompositionCompositionString::String(charString::String(char ** strstr){){

    if(strif(str != NULL){!= NULL){

    ptrptr = new char[strlen(str)+1];= new char[strlen(str)+1];

    strcpy(ptrstrcpy(ptr,, strstr););}}

    elseelseptrptr = NULL;= NULL;

    coutcout

  • 8/3/2019 Computer Notes - Friend Functions

    9/34

    CompositionCompositionStudent class is modified asStudent class is modified asfollows:follows:

    class Student{class Student{

    private:private:

    floatfloat gpagpa;;intint rollNumberrollNumber;;

    String name;String name;

    public:public:

    Student(charStudent(char *=NULL,*=NULL, intint=0, float=0.0);=0, float=0.0);

    };};

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    10/34

    CompositionComposition

    Student class continued:Student class continued:Student::Student(charStudent::Student(char ** n,intn,int roll,roll,

    float g):float g): name(nname(n)){{coutcout

  • 8/3/2019 Computer Notes - Friend Functions

    11/34

    CompositionComposition

    Main Function:Main Function:

    intintmain(){main(){StudentStudent aStudent("FakhiraStudent("Fakhir", 899,", 899,

    3.1);3.1);coutcout

  • 8/3/2019 Computer Notes - Friend Functions

    12/34

    CompositionCompositionOutput:Output:

    OverloadedOverloadedConstructor::StringConstructor::String....

    Constructor::StudentConstructor::Student....

    Name:Name: FakhirFakhir

    Destructor::StudentDestructor::Student....Destructor::StringDestructor::String....

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    13/34

    CompositionCompositionNow consider the following case:Now consider the following case:

    String

    name: char*

    String()

    String(char *)

    ~String()

    Date()

    Date(int,int,int)

    Date(const Date &)

    Student()

    Student( char *,

    const Date &, int, float)

    SetName(char *) : voidGetName() : char *

    ~Student()

    name : StringbirthDate : Date

    Student

    day: int

    Month: intyear: int

    Date

  • 8/3/2019 Computer Notes - Friend Functions

    14/34

    CompositionCompositionStudent class is modified asStudent class is modified asfollows:follows:

    class Student{class Student{

    private:private:

    DateDatebirthDatebirthDate;;

    String name;String name;

    public:public:

    Student(charStudent(char *, const Date &,*, const Date &, intint,,float);float);

    ~Student();~Student();

    };};

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    15/34

    CompositionComposition

    Student class continued:Student class continued:Student::Student(charStudent::Student(char * n, const Date & d,* n, const Date & d, intint

    roll,roll, flaotflaot g):g): name(n),birthDate(dname(n),birthDate(d)){{

    coutcout

  • 8/3/2019 Computer Notes - Friend Functions

    16/34

    CompositionComposition

    Main function:Main function:

    intintmain(){main(){Date _date(31, 12, 1982);Date _date(31, 12, 1982);

    StudentStudent aStudent("FakhiraStudent("Fakhir",",

    _date,899,3.5);_date,899,3.5);

    return 0;return 0;

    }}http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    17/34

    CompositionCompositionOutput:Output:

    OverloadedOverloadedConstructor::DateConstructor::Date....

    CopyCopy Constructor::DateConstructor::Date....

    OverloadedOverloadedConstructor::StringConstructor::String....Constructor::StudentConstructor::Student....

    Destructor::StudentDestructor::Student....

    Destructor::StringDestructor::String....Destructor::DateDestructor::Date....

    Destructor::DateDestructor::Date....

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    18/34

    AggregationAggregationComposition vs. AggregationComposition vs. Aggregation

    Aggregation is aAggregation is a weak relationshipweak relationship

    Room(char *, int)~Room()

    FoldChair(int) : bool

    Chair()

    DoSomething() : voidFoldChair() : bool

    UnFoldChair() : bool

    ~Chair()

    area : float

    chairs[50]:Chair *

    Room

    Chair

  • 8/3/2019 Computer Notes - Friend Functions

    19/34

    AggregationAggregationIn aggregation, a pointer or referenceIn aggregation, a pointer or reference

    to an object is created inside a classto an object is created inside a class

    The subThe sub--object has a life that isobject has a life that is NOTNOT

    dependant on the life of its master classdependant on the life of its master classe.ge.g::

    Chairs can be moved inside or outside at anytimeChairs can be moved inside or outside at anytime

    When Room is destroyed, the chairs may orWhen Room is destroyed, the chairs may or maymaynotnot be destroyedbe destroyed

  • 8/3/2019 Computer Notes - Friend Functions

    20/34

    AggregationAggregationclass Room{class Room{private:private:

    float area;float area;

    Chair * chairs[50];Chair * chairs[50];

    Public:Public:Room();Room();

    voidvoidAddChair(ChairAddChair(Chair *,*, intint chairNochairNo););

    Chair *Chair * GetChair(intGetChair(int chairNochairNo););

    boolbool FoldChair(intFoldChair(int chairNochairNo););

    };};

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    21/34

  • 8/3/2019 Computer Notes - Friend Functions

    22/34

    AggregationAggregationChair *Chair * Room::GetChair(intRoom::GetChair(int chairNochairNo){){

    if(chairNoif(chairNo >= 0 &&>= 0 && chairNochairNo< 50)< 50)returnreturn chairs[chairNochairs[chairNo];];

    elseelse

    return NULL;return NULL;

    }}

    boolbool Room::FoldChair(intRoom::FoldChair(int chairNochairNo){){

    if(chairNoif(chairNo >= 0 &&>= 0 && chairNochairNo< 50)< 50)

    returnreturn chairs[chairNochairs[chairNo]]-->>FoldChairFoldChair();();elseelse

    return false;return false;

    }}

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    23/34

    AggregationAggregationintintmain(){main(){

    Chair ch1;Chair ch1;{{

    Room r1;Room r1;

    r1.AddChair(&ch1, 1);r1.AddChair(&ch1, 1);r1.FoldChair(1);r1.FoldChair(1);

    }}

    ch1.UnFoldChair(1);ch1.UnFoldChair(1);

    return 0;return 0;

    }}http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    24/34

    Friend FunctionsFriend FunctionsConsider the following class:Consider the following class:

    class X{class X{

    private:private:

    intint a, b;a, b;public:public:

    voidvoidMemberFunctionMemberFunction();();

    }}

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    25/34

    Friend FunctionsFriend FunctionsGlobal function:Global function:

    voidvoidDoSomething(XDoSomething(X objobj){){

    obj.aobj.a = 3;= 3; //Error//Error

    obj.bobj.b = 4;= 4; //Error//Error

    }}

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    26/34

    Friend FunctionsFriend FunctionsIn order to access the member variables of the class, functionIn order to access the member variables of the class, functiondefinition must be made a friend function:definition must be made a friend function:

    class X{class X{

    private:private:

    intint a, b;a, b;

    public:public:

    friend voidfriend voidDoSomething(XDoSomething(X objobj););

    }}

    Now the functionNow the function DoSomethingDoSomething can access data members ofcan access data members ofclass Xclass X

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    27/34

    Friend FunctionsFriend Functions

    Prototypes of friend functionsPrototypes of friend functionsappear in the class definitionappear in the class definition

    But friend functions are NOTBut friend functions are NOTmember functionsmember functions

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    28/34

    Friend FunctionsFriend FunctionsFriend functions can be placed anywhere in the classFriend functions can be placed anywhere in the class

    without any effectwithout any effectAccessAccess specifiersspecifiers dondont affect friend functions ort affect friend functions orclassesclasses

    class X{class X{

    ......

    private:private:

    friend voidfriend voidDoSomething(XDoSomething(X););

    public:public:friend voidfriend voidDoAnything(XDoAnything(X););

    ......

    };}; http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    29/34

    Friend FunctionsFriend FunctionsWhile the definition of the friend function is:While the definition of the friend function is:

    voidvoidDoSomething(XDoSomething(X objobj){){

    obj.aobj.a = 3;= 3; // No Error// No Error

    obj.bobj.b = 4;= 4; // No Error// No Error

    }}

    friendfriendkeyword is not given in definitionkeyword is not given in definition

  • 8/3/2019 Computer Notes - Friend Functions

    30/34

    Friend FunctionsFriend FunctionsIf keywordIf keyword friendfriendis used in the functionis used in the functiondefinition, itdefinition, its a syntax errors a syntax error

    //Error//Error

    friend voidfriend voidDoSomething(XDoSomething(X objobj){){

    }}

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    31/34

    Friend ClassesFriend ClassesSimilarly, one class can also be made friend ofanother class:

    class X{

    friend class Y;

    };

    Member functions of class Y can accessprivate data members of class X

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    32/34

    Friend ClassesFriend ClassesExample:

    class X{friend class Y;

    private:int x_var1, x_var2;

    ...

    };

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    33/34

    Friend ClassesFriend Classesclass Y{

    private:int y_var1, y_var2;X objX;

    public:void setX(){objX.x_var1 = 1;

    }

    };

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Friend Functions

    34/34

    Friend ClassesFriend Classes

    int main(){Y objY;objY.setX();return 0;

    }

    http://ecomputernotes.com