13878 Constructors

download 13878 Constructors

of 49

Transcript of 13878 Constructors

  • 8/8/2019 13878 Constructors

    1/49

    Default Constructors

    The default constructordoes not includeparameters, and is called for any declaredobjects of its class to which you do not

    pass arguments Remember that you define and declare

    constructor functions the same way youdefine other functions, although you do notinclude a return type because constructorfunctions do not return values

    1

  • 8/8/2019 13878 Constructors

    2/49

    Constructor Function

    2

    A Constructor is a special member functionwhose task is to initialize the object of its

    class. Its name is same as class name.

    The Constructor is invoked whenever an

    object of its associated class is created. It

    is called constructor because it constructs

    the values of data members of the class.

  • 8/8/2019 13878 Constructors

    3/49

    class integer

    {int m, n;

    public:

    integer(); //constructor declared

    };

    integer::integer() //constructor defined

    {

    m=0;n=0;

    }3

  • 8/8/2019 13878 Constructors

    4/49

    when a class contains constructor, object ofclass is

    initialized automatically.

    integer int1; //object int1 created

    Not only creates object int1 but also initializes

    its data members m and n to zero. There is no need to write any statement to

    invoke constructor function( as we do withnormal member functions)

    4

  • 8/8/2019 13878 Constructors

    5/49

    Characteristics:

    They should be declared in public section. They are invoked automatically when objectsare created.

    They do not have return types, not even void

    and therefore cannot return values. Like other C++ functions, they can have

    default arguments.

    Constructors cannot be virtual

    We cannot refer to their addresses

    They cannot be inherited, though a derivedclass can call the base class constructor

    5

  • 8/8/2019 13878 Constructors

    6/49

    Default Constructors

    A constructor that accepts no parameter iscalled default constructor.

    The default constructor for class a is A::A().

    If no such constructor is defined, then compiler

    supplies a default constructor. A statement A a;invokes default constructor

    class integer

    { int m,n;public:

    integer( ); // default constructor declared

    };6

  • 8/8/2019 13878 Constructors

    7/49

    Simple Program

    7

    // default constructor#include

    class integer

    {

    int m,n;

    public:Integer(); // constructor declared

    };

    integer :: integer( ) // constructor defined

    {

    m= 0;

    n=0;

    }

  • 8/8/2019 13878 Constructors

    8/49

    Parameterized Constructors The constructor that can take arguments is called parameterized

    constructor.

    Class integer

    {

    Int m, n;Public :

    Integer (int x, int y); // parameterized constructor

    };

    Integer::integer(int x,int y)

    {

    m=x;

    n=y;

    }

    8

  • 8/8/2019 13878 Constructors

    9/49

    When a constructor is parameterized,

    integer int1;

    may not work. We must pass the initial values as

    arguments to constructor fn when object is

    created. By calling constructor explicitly

    By calling constructor implicitly

    9

  • 8/8/2019 13878 Constructors

    10/49

    integer int1 = integer(0,100);

    //explicitly called

    integer int1(0,100) //implicitly

    called.

    Shorthand method.

    10

  • 8/8/2019 13878 Constructors

    11/49

    # include

    Class integer

    {

    Int m,n;

    Public:

    Integer(int,int)Void display()

    {

    Cout

  • 8/8/2019 13878 Constructors

    12/49

    Constructor function can also be defined as inline

    function

    Constructor function can be defined using inline.

    Class integer

    {

    int m,n;

    public:integer(int x,int y) //inline constructor

    {

    m=x; y=n;}

    };

    12

  • 8/8/2019 13878 Constructors

    13/49

    Parameters of a constructor can be of any type except that

    of class to which it belongs

    class A

    {

    public:

    A(A); // isillegal};

    13

  • 8/8/2019 13878 Constructors

    14/49

    ons ruc or can accep a

    reference to its own class as a

    parameter.class A

    {

    ..

    public:

    A(A &i); //known as copy constructor};

    14

  • 8/8/2019 13878 Constructors

    15/49

    Multiple Constructors in a class

    integer(); //No arguments

    integer(int , int); // Two arguments

    In the first case

    ___________________________

    In the second case

    _________________________

    C++ permits us to use both these

    constructors in the same class. 15

  • 8/8/2019 13878 Constructors

    16/49

    Multiple constructors in a classClass integer

    { int m,n;

    public:

    integer() { m=0; n=0; } //consructor 1

    integer(int a,int b) { m=a;n=b; } //constructor 2

    integer(integer &i) { m=i.m; n=i.n; } //constructor 3

    };

    Statementinteger I1; //automatically invoke the 1st constructor

    integer I2(10,20); //call the 2nd constructor

    integer I3(I2); // wud invoke 3rd constructor which

    copies the value of I2 into I3 16

  • 8/8/2019 13878 Constructors

    17/49

    COPY CONSTRUCTOR

    A copy constructor is used to declare andinitialize object of another class.

    Integer I3(I2); would define object I3 and

    at the same time would initialize it to valueof I2.

    Another form :

    Integer I3=I2; Process of initializing through copy

    constructor is known as copy initialization

    17

  • 8/8/2019 13878 Constructors

    18/49

    When we say that constructor is

    overloaded?

    When more than one constructor function isdefined in a class,we say that constructor is

    overloaded.

    18

  • 8/8/2019 13878 Constructors

    19/49

    Constructors with default

    argumentscomplex(float real, float imag=0);

    //The default value for argument imag is zero.

    complex(5.0); //assigns 5.0 to real

    complex C(2.0,5.0); //assigns 2.0 to real and5.0 to imag

    19

  • 8/8/2019 13878 Constructors

    20/49

    Distinguish between default constructor and default argument

    constructor

    A::A(int =0) //default constructor can be

    called with either one argument or no

    arguments.

    When called with no arguments ,it becomes a

    default constructor.

    When both these forms are used in a class ,it

    causes ambiguity for a statement such as

    A a; // whether to call A::A() orA::A(int=0)020

  • 8/8/2019 13878 Constructors

    21/49

    Copy Constructor

    y

    Copy Constructor are always used whenthe compiler has to create a temporaryobject of a class .The copy constructor areused in the following situations:-

    yThe Initialization of an object by anotherobject of the same class.

    yReturn of object as a function value.

    y

    Stating the object as by value parametersof a function.

    21

  • 8/8/2019 13878 Constructors

    22/49

    Copy Constructor Example with Program

    //fibonacci series using copy constructor

    #include

    Class fibonacci {

    Private :

    int f0,f1,fib;

    Public :

    Fiboancci () // constructor

    {

    f0=0;

    f1=1;

    fib=f0+f1;

    }

    Fibonacci (fibonacci &ptr) // copy construtor

    //CC takes reference to an object of same class

    as argument

    {

    f0=ptr.f0;

    f1=ptr.f1;

    fib=prt.fib; 22

    Void increment ( )

    {

    f0=f1;

    f1=fib;

    fib=f0+f1;

    }

    Void display ( )

    {

    Cout

  • 8/8/2019 13878 Constructors

    23/49

    #include void display (void)

    Using namespace std ; { cout

  • 8/8/2019 13878 Constructors

    24/49

    Dynamic Initialization Of Objects

    Class objects can be intialized dynamicallytoo.

    The initial value of an object may be provided

    during run time.

    1.We can provide various initialization formats,

    using overloaded constructor

    2.Provides the flexibility of using different

    format of data at run time depending upon

    the situation24

    Advantage of Dynamic Initialization

  • 8/8/2019 13878 Constructors

    25/49

    25

    class fixed_deposit

    {

    long int p_amount;

    int years;float rate;

    float r_value;

    public:

    fixed_deposit(){

    }

    fixed_deposit(long int p , int y , float r=0.12);

    fixed_deposit(long int p , int y , int r);void display(void);

    };

  • 8/8/2019 13878 Constructors

    26/49

    26

    fixed_deposit :: fixed_deposit(long int p, int y , float r)

    {

    _____________;

    }fixed_deposit::fixed_deposit(long int p , int y , int r)

    {

    }void fixed_deposit::display(void)

    {

    }

    int main()

    {

    fixed_deposit fd1,fd2,fd3;long int p;

    int y;

    float r;

    int R;

    coutp>>y>>R;

    fd1=fixed_deposit(p,y,R);

    coutp>>y>>r;

    fd1=fixed_deposit(p,y,r);

    coutp>>y;

    fd3=fixed_deposit(p,y);

    fd1.deposit();

    fd2.deposit();

    fd3.deposit();

  • 8/8/2019 13878 Constructors

    27/49

    Dynamic Constructor(DC)

    DC can also be used to allocate memorywhile creating objects.

    This will enable the system to allocate right

    amount of memory for each object when theobjects are not of the same size.

    Resulting in: --------------------

    Allocation of memory to objects at the time of

    their construction is known as dynamic

    construction of objects.

    Memory is allocated with the help of27

    new

    operator.

  • 8/8/2019 13878 Constructors

    28/49

    28

    class String

    {

    char *name;

    int length;public:

    String()

    {

    length=0;

    name=new char[length+1];}

    String(char *s)

    {

    length=strlen(s);name=new char[length+1];

    strcpy(name,s);

    }

    void display() { cout

  • 8/8/2019 13878 Constructors

    29/49

    Destructors

    Just as a default constructor is called when aclass object is first instantiated, a defaultdestructor is called when the object isdestroyed

    A default destructor cleans up any resourcesallocated to an object once the object isdestroyed

    The default destructor is sufficient for mostclasses, except when you have allocatedmemory on the heap

    29

  • 8/8/2019 13878 Constructors

    30/49

    Destructors

    You create a destructor function using the

    name of the class, the same as a

    constructor

    A destructor is commonly called in two

    ways:

    When a stack object loses scope because the function inwhich it is declared ends

    When a heap object is destroyed with the delete operator

    30

  • 8/8/2019 13878 Constructors

    31/49

    Syntax rules for writing a destructor function

    :

    A destructor function name is the same asthat of the class it belongs except that thefirst character of the name must be a tilde (~).

    It is declared with no return types ( not even

    void) since it cannot even return a value. It cannot de declared static ,const or volatile.

    It takes no arguments and therefore cannotbe overloaded.

    It should have public access in the classdeclaration.

    Cant be overloaded or inherited.

    31

  • 8/8/2019 13878 Constructors

    32/49

    Class employee

    {

    Private :Char name[20];

    Int ecode ;

    Char address[30];Public :

    Employee ( ) // constructor

    ~ employee ( ) // destructor

    Void getdata( );

    Void display( );

    };

    32

  • 8/8/2019 13878 Constructors

    33/49

    33

    #include

    #include

    Class account {

    Private :Float balance;

    Float rate;

    Public:

    Account( ); // constructor name

    ~ account ( );// destructor name

    Void deposit( );

    Void withdraw( );

    Void compound( );

    Void getbalance( );

    Void menu( );

    }; //end of class definitionAccount :: account( ) // constructor

    {

    Coutbalance;

    }

    Account :: ~account( ) // destructor

  • 8/8/2019 13878 Constructors

    34/49

    34

    {

    Cout

  • 8/8/2019 13878 Constructors

    35/49

    #include

    Using namespace std;

    Int count =0;Class alpha

    {

    Public :

    Alpha()

    {

    Count ++;

    Cout

  • 8/8/2019 13878 Constructors

    36/49

    Cout

  • 8/8/2019 13878 Constructors

    37/49

    Cout

  • 8/8/2019 13878 Constructors

    38/49

    Static Class Members

    You can use the static keyword when declaring class

    members Static class members are somewhat different from static

    variables

    When you declare a class member to be static, only onecopy of that class member is created during a programsexecution, regardless of how many objects of the class youinstantiate.

    Static members can be of any one of the groups : public ,

    private and protected ,but not a global data.

  • 8/8/2019 13878 Constructors

    39/49

    It is initialized to zero when the first object is created. No

    other initialization is permitted.

    Only one copy of that member is created for the entire

    class and shared by all the objects of the class, no matterhow many object are created.

    It is visible only within the class, but lifetime is entire the

    program.

    The general syntax of the static data member is :-Class user_defined_name

    {

    Private :

    Static data_type variables ;

    Static data_type variables ;

    Public :

    ---};39

  • 8/8/2019 13878 Constructors

    40/49

    A static data member of a class has the following properties

    1. The access rule of the data member of a class is same forthe static data member also.

    example : if a static member is declared as a private category

    of a class, then non member functions cannot access

    these members. If a static member is declared as public,

    then any member of the class can access.

    2. Whenever a static data member is declared and it has only

    a single copy , it will be shared by all the instance of class.

    That is, the static member becomes global instances of

    the class.3. The static data member should be created and initialized

    before main() function control block begins

  • 8/8/2019 13878 Constructors

    41/49

    #include

    Using namespace std;

    Class item

    {

    Static int count;

    Int number;

    Public :

    Void getdata(int a)

    {

    Number=a;

    Count++;

    }

    Void getcount(void)

    {

    Cout

  • 8/8/2019 13878 Constructors

    42/49

    Int item :: count;

    Int main( )

    {Item a,b,c; //count is intialized to zero

    a.getcount( ); // display count

    b.getcount( );

    c.getcount();

    a.getdata(100); // getting data into objects a,b,c

    b.getdata(200);

    c.getdata(300);Cout

  • 8/8/2019 13878 Constructors

    43/49

    IMPORTANT POINTS :

    The Type and scope of each static member variable must be defined outside the classdefination.

    Int item :: count; // definition of static datamember

    This is necessary because the static datamembers are stored separately rather than asapart of an object. Since they are associatedwith class itself rather than with any classobject, they are also known as class variables.

    The static variable count is initialized to zerowhen the object are created. The count isincremented whenever the data is read into anobject.

    43

  • 8/8/2019 13878 Constructors

    44/49

    Count

    44

    A B C

    In this count data member is static variable within the

    class and a,b,c are objects. Because there is only one

    copy of count shared by all the three objects.

    Initial count 0,1,2,3

  • 8/8/2019 13878 Constructors

    45/49

    We can initialize the static variable

    Int item : : count =10;

    45

  • 8/8/2019 13878 Constructors

    46/49

    Static MemberFunctions

    Like static member variable, we can also have static member functions. A

    member function that is declared static has following prosperities.

    A static function can have access to only other static members

    (functions or variables) declared in the same class.

    A static member function can be called using the class name( instead

    of its objects) as below :-

    Class name :: function-name;

  • 8/8/2019 13878 Constructors

    47/49

    //Static member functions :

    #include

    Using namespace std;

    Class test{ int code;

    Static int count; // static member variable

    Public:

    Void setcode( )

    {

    Code=++count;

    }

    Void showcode()

    {

    Cout

  • 8/8/2019 13878 Constructors

    48/49

    Int test : : count ;

    Int main()

    {

    Test t1,t2;T1.setcode();

    T2.setcode();

    Test::showcount() ; // accessing static function

    Test t3;

    T3.setcode();

    Test:: showcount( );

    T1.showcode();

    T2.showcode();

    T3.showcode();Return 0;

    }

    48

  • 8/8/2019 13878 Constructors

    49/49

    Important note :

    The statement

    Code=++count is executed whenever setcode() function isinvoked and the current value of count is assigned to

    code. Since each object has its own copy of the code ,

    the value contained in code represent a unique of its

    object.

    Remember that

    Static void showcount ()

    {

    Cout