Computer Notes - Constructor

download Computer Notes - Constructor

of 35

Transcript of Computer Notes - Constructor

  • 8/3/2019 Computer Notes - Constructor

    1/35

    ConstructorConstructor

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    2/35

    ReviewReview

    Member functions implementationMember functions implementation

    ConstructorsConstructors

    Constructors overloadingConstructors overloadingCopy constructorsCopy constructors

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    3/35

    Copy ConstructorCopy Constructor

    Copy constructor are used when:Copy constructor are used when:

    Initializing an object at the time ofInitializing an object at the time of

    creationcreation

    When an object is passed by value to aWhen an object is passed by value to a

    functionfunction

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    4/35

    ExampleExample

    void func1(Student student){void func1(Student student){

    }}

    intintmain(){main(){StudentStudent studentA(studentA(AhmadAhmad););

    StudentStudent studentBstudentB == studentAstudentA;;func1(studentA);func1(studentA);

    }}http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    5/35

    Copy Constructor (contd.)Copy Constructor (contd.)

    Student::Student(Student::Student(const Student &const Student &objobj){){

    rollNorollNo == obj.rollNoobj.rollNo;;name =name = obj.nameobj.name;;

    GPA =GPA = obj.GPAobj.GPA;;}}

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    6/35

    Shallow CopyShallow Copy

    When we initialize one object withWhen we initialize one object with

    another then the compiler copies stateanother then the compiler copies state

    of one object to the otherof one object to the other

    This kind of copying is called shallowThis kind of copying is called shallow

    copyingcopying

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    7/35

    ExampleExampleStudent studentA(Ahmad);

    GPAGPA

    NameName

    RollNnRollNn

    studentBstudentB

    Heap

    A

    H

    M

    A

    D

    GPAGPA

    NameName

    RollNnRollNn

    studentAstudentA

    Student studentB = studentA;

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    8/35

    Exampleint main(){

    Student studentA(Ahmad,1);

    {

    Student studentB = studentA;

    GPAGPA

    NameName

    RollNnRollNn

    studentBstudentB

    Heap

    A

    H

    M

    A

    D

    GPAGPA

    NameName

    RollNnRollNn

    studentAstudentA

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    9/35

    ExampleExampleint main(){

    Student studentA(Ahmad,1);

    {

    Student studentB = studentA;}

    }

    HeapGPAGPA

    NameName

    RollNnRollNn

    studentAstudentA

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    10/35

    Copy Constructor (contd.)Copy Constructor (contd.)

    Student::Student(Student::Student(const Student &const Student & objobj){){

    intint lenlen == strlen(obj.namestrlen(obj.name););

    name = new char[len+1]name = new char[len+1]

    strcpy(namestrcpy(name,, obj.nameobj.name););

    /*copy rest of the data members*//*copy rest of the data members*/

    }}

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    11/35

    Exampleint main(){Student studentA(Ahmad,1);

    {

    Student studentB = studentA;

    A

    H

    MA

    D

    GPAGPANameName

    RollNnRollNn

    studentAstudentA

    GPAGPA

    NameName

    RollNnRollNnstudentBstudentB

    A

    HM

    A

    D

  • 8/3/2019 Computer Notes - Constructor

    12/35

    ExampleExampleint main(){

    Student studentA(Ahmad,1);

    {Student studentB = studentA;}

    }

    HeapGPAGPANameName

    RollNnRollNn

    studentAstudentA

    A

    HM

    A

    D

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    13/35

    Copy Constructor (contd.)Copy Constructor (contd.)

    Copy constructor is normally used toCopy constructor is normally used toperform deep copyperform deep copy

    If we do not make a copyIf we do not make a copyconstructor then the compilerconstructor then the compiler

    performs shallow copyperforms shallow copy

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    14/35

    DestructorDestructor

    Destructor is used to free memoryDestructor is used to free memory

    that is allocated through dynamicthat is allocated through dynamic

    allocationallocation

    Destructor is used to perform houseDestructor is used to perform house

    keeping operationskeeping operations

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    15/35

    Destructor (contd.)Destructor (contd.)

    Destructor is a function withDestructor is a function withthe same name as that of class,the same name as that of class,

    but preceded with a tildebut preceded with a tilde~~

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    16/35

    ExampleExampleclass Studentclass Student

    {{

    public:public:

    ~Student(){~Student(){if(name){if(name){

    delete []name;delete []name;

    }}

    }}

    }}

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    17/35

    OverloadingOverloading

    Destructors cannot beDestructors cannot beoverloadedoverloaded

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    18/35

    Sequence of CallsSequence of Calls

    Constructors and destructors areConstructors and destructors arecalled automaticallycalled automatically

    Constructors are called in theConstructors are called in the

    sequence in which object is declaredsequence in which object is declaredDestructors are called in reverse orderDestructors are called in reverse order

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    19/35

    ExampleExampleStudent::Student(char *Student::Student(char * aNameaName){){

    coutcout

  • 8/3/2019 Computer Notes - Constructor

    20/35

    ExampleExampleintintmain()main()

    {{

    StudentStudent studentB(studentB(AliAli););

    StudentStudent studentA(studentA(AhmadAhmad););

    return 0;return 0;

    }}

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    21/35

    ExampleExample

    Output:Output:

    Ali ConsAli Cons

    Ahmad ConsAhmad ConsAhmadAhmad DestDest

    AliAli DestDest

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    22/35

    Accessor FunctionsAccessor Functions

    Usually the data member are defined inUsually the data member are defined in

    private part of a classprivate part of a class information hidinginformation hiding

    Accessor functions are functions that areAccessor functions are functions that are

    used to access these private dataused to access these private datamembersmembers

    Accessor functions also useful in reducingAccessor functions also useful in reducingerrorerror

  • 8/3/2019 Computer Notes - Constructor

    23/35

    ExampleExampleAccessing Data MemberAccessing Data Member

    class Student{class Student{

    intint rollNorollNo;;

    public:public:

    voidvoidsetRollNo(intsetRollNo(int aRollNoaRollNo){){

    rollNorollNo == aRollNoaRollNo;;}}

    };}; http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    24/35

    ExampleExampleAvoiding ErrorAvoiding ErrorvoidvoidStudent::setRollNo(intStudent::setRollNo(int aRollNoaRollNo){){

    if(aRollNoif(aRollNo< 0){< 0){rollNorollNo = 0;= 0;

    }}

    elseelse

    {{

    rollNorollNo == aRollNoaRollNo;;}}

    }}

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    25/35

    ExampleExample -- GetterGetterclass Student{class Student{

    intint rollNorollNo;;

    public:public:

    intint getRollNogetRollNo(){(){

    returnreturn rollNorollNo;;

    }}

    };};http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    26/35

    thisthis PointerPointerclass Student{class Student{

    intint rollNorollNo;;char *name;char *name;

    float GPA;float GPA;

    public:public:

    intint getRollNogetRollNo();();

    voidvoidsetRollNo(intsetRollNo(int aRollNoaRollNo););

    };};http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    27/35

    thisthis PointerPointerThe compiler reserves space for theThe compiler reserves space for the

    functions defined in the classfunctions defined in the class

    Space for data is not allocated (Space for data is not allocated (since nosince no

    object is yet createdobject is yet created))

    Function SpacegetRollNo(),

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    28/35

    thisthis PointerPointerStudent sStudent s11,, s2s2,, s3s3;;

    Function SpacegetRollNo(),

    s1(rollNo,)

    s2(rollNo,)

    s3(rollNo,)

  • 8/3/2019 Computer Notes - Constructor

    29/35

    thisthis PointerPointerFunction space is common for everyFunction space is common for every

    variablevariable

    Whenever a new object is created:Whenever a new object is created:

    Memory is reserved for variables onlyMemory is reserved for variables only Previously defined functions are usedPreviously defined functions are used

    over and over againover and over again

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    30/35

    thisthis PointerPointerMemory layout for objects created:Memory layout for objects created:

    s1

    rollNo,

    Function Space

    getRollNo(),

    s2

    rollNo,

    s3

    rollNo,

    s4

    rollNo,

    How does the functions know on which

    object to act?

  • 8/3/2019 Computer Notes - Constructor

    31/35

    thisthis PointerPointerAddress of each object is passed to the callingAddress of each object is passed to the calling

    functionfunctionThis address isThis address is deferenceddeferenced by the functions andby the functions and

    hence they act on correct objectshence they act on correct objects

    address

    s1

    rollNo,

    s2

    rollNo,

    s3

    rollNo,

    s4

    rollNo,

    address address address

    The variable containing the self-address is

    called this pointer

  • 8/3/2019 Computer Notes - Constructor

    32/35

    PassingPassing thisthisPointerPointerWhenever a function is called theWhenever a function is called the thisthispointer ispointer is

    passed as a parameter to that functionpassed as a parameter to that functionFunction withFunction with nnparameters is actually calledparameters is actually called

    withwith n+1n+1parametersparameters

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    33/35

    ExampleExamplevoidvoidStudent::setName(charStudent::setName(char *)*)

    is internally represented asis internally represented as

    voidvoidStudent::setName(charStudent::setName(char *,*,

    const Student *)const Student *)

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    34/35

    Declaration of thisDeclaration of thisDataTypeDataType * const this;* const this;

    http://ecomputernotes.com

  • 8/3/2019 Computer Notes - Constructor

    35/35

    Compiler Generated CodeCompiler Generated CodeStudent::Student(){Student::Student(){

    rollNorollNo = 0;= 0;

    }}

    Student::Student(){Student::Student(){

    thisthis-->>rollNorollNo = 0;= 0;}}

    http://ecomputernotes.com