Constructor,destructors cpp


Published on

Published in: Education, Technology, Business
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Constructor,destructors cpp

  1. 1. ObjectivesIn this chapter you will learn: About default constructors How to create parameterized constructors How to work with initialization lists How to create copy constructors 1
  2. 2. Advanced Constructors Constructors can do more than initialize data members They can execute member functions and perform other types of initialization routines that a class may require when it first starts 2
  3. 3. Default Constructors The default constructor does not include parameters, and is called for any declared objects of its class to which you do not pass arguments Remember that you define and declare constructor functions the same way you define other functions, although you do not include a return type because constructor functions do not return values 3
  4. 4. Constructor Function 4 A Constructor is a special member function whose task is to initialize the object of its class. It is special because it 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.
  5. 5. Default Constructors The constructor function in Figure is an example of a default constructor In addition to initializing data members and executing member functions, default constructors perform various types of behind-the-scenes class maintenance 5
  6. 6. Simple Program 6 // default constructor #include<iostream> Using namespace std; Class integer { Int m,n; Public: Integer(void); // constructor declared Void getinfo( ); }; Integer :: integer void( ) // constructor defined { m= 0; n=0; }
  7. 7. Parameterized Constructors The constructor integer( ) define above initialize the data members of all the objects to zero. However is practice it may be necessary to initialize the various data elements of different objects with different values, when they are created. A parameterized constructor allows a client to pass initialization values to your class during object instantiation Instead of assigning default values, you can allow a client to pass in the value for these data members by designing the constructor function with parameters. 7
  8. 8. 8 Class integer { Int m, n; Public : Integer (int x, int y); }; Integer :: integer(int x,int y) { m= x; n=y; } By Calling the Constructor explicitly By Calling the consructor implicitly
  9. 9.  integer int1 = integer(0,100); Explicitly called Integer int1(0,100) Implicitly called. Shorthand method. 9
  10. 10. Copy Constructor There will be times when you want to instantiate a new object based on an existing object C++ uses a copy constructor to exactly copy each of the first object’s data members into the second object’s data members in an operation known as member wise copying A copy constructor is a special constructor that is called when a new object is instantiated from an old object 10
  11. 11. Copy Constructor The syntax for a copy constructor declaration is class_name :: class_name (class_name &ptr) The Copy Constructor may be used in the following format also using a const keyword. class_name :: class_name (const class_name & ptr) Copy Constructor are always used when the compiler has to create a temporary object of a class object.The copy constructor are used in the following situations:- The Initialization of an object by another object of the same class. Return of object as a function value. Stating the object as by value parameters of a function. 11
  12. 12. Copy Constructor Example with Program //fibonacci series using copy constructor #include<iostream> Using namespaces std ; Class fibonacci { Private : Unsigned long int f0,f1,fib; Public : Fiboancci () // constructor { F0=0; F1=1; Fib=f0+f1; } Fibonacci (fibonacci &ptr) // copy construtor { F0=ptr.f0; F1=ptr.f1; Fib=prt.fib; } 12 Void increment ( ) { F0=f1; F1=fib; Fib=f0+f1; } Void display ( ) { Cout<<fib<<‘/t’; } }; Void main( ) { Fibonacci number ; For(int i=0;i<=15;++i) { Number.display(); Number.increment(); } }
  13. 13. #include<iostream> void display (void) Using namespace std ; { cout<<id; Class code // class name } { }; Int id; int main() Public : { Code() code A(100);//object A is created // constructor name same as class name code B(A); // copy const. called { code C= A; // CC called again } code D; // D is created, not intilized Code(int a ) { // constructor again D=A; // C C not called Id=a; cout<<“n” id of A:=A.display(); } cout<<“n” id of B:=B.display(); Code (code &x) // copy constuctor cout<<“n” id of C:=C.display(); {; // copy in the value cout<<“n” id of D:=D.display(); } return 0; } 13
  14. 14. Destructors Just as a default constructor is called when a class object is first instantiated, a default destructor is called when the object is destroyed A default destructor cleans up any resources allocated to an object once the object is destroyed The default destructor is sufficient for most classes, except when you have allocated memory on the heap 14
  15. 15. 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 in which it is declared ends When a heap object is destroyed with the delete operator 15
  16. 16. Syntax rules for writing a dectructor function : A destructor function name is the same as that of the class it belongs except that the first 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 cannot be overloaded. It should have public access in the class declaration.  16
  17. 17. Class employee { Private : Char name[20]; Int ecode ; Char address[30]; Public : Employee ( ); // constructor ~ Employee ( ); // destructor Void getdata( ); Void display( ); }; 17
  18. 18. 18 #include<iostream> #include<stdio> 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 definition Account :: account( ) // constructor { Cout<<“enter the initial balancen”; Cin>>balance; } Account :: ~account( ) // destructor
  19. 19. 19 { Cout<<“data base has been deletedn” } // to deposit Void account ::deposit( ) { Float amount; Cout<<“how much amount want to deposit”; Cin>>amount; Balance=balace+amount ; } // the program is not complete , the purpose is to clear the function of constructor and destructor
  20. 20. #include<iostream> Using namespace std; Int count =0; Class alpha { Public : Alpha() { Count ++; Cout <<“n No. of object created “<<count; } ~alpha() { 20
  21. 21. Cout<<“n No. of object destroyed “<<count; Count --; } }; Int main() { cout<<“n n Enter mainn”; Alpha A1 A2 A3 A4; { Cout<<“nn Enter block 1n”; Alpha A5; } { cout<<“nn Enter Block 2 n”; Alpha A6; } 21
  22. 22. Cout<<“n n RE-enter Mainn”; Return 0; Enter Block 2 No. of object created :5 } Re-Enter Main No. of object destroyed Output : Enter Main 4,3,2,1 No. of object created 1 No. of object created 2 No. of object created 3 No. of object created 4 Enter Block 1 No. ofobject created 5 No. of object Destroyed 5 22
  23. 23. 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 one copy of that class member is created during a program’s execution, regardless of how many objects of the class you instantiate Figure 7-38 illustrates the concept of the static and non-static data members with the Payroll class 23
  24. 24. Multiple Class Objects with Static and Non-Static Data Members 24
  25. 25. Static Data Members You declare a static data member in your implementation file using the syntax static typename;, similar to the way you define a static variable static data members are bound by access specifiers, the same as non-static data members This means that public static data members are accessible by anyone, whereas private static data members are available only to other functions in the class or to friend functions 25
  26. 26. Static Data Members You could use a statement in the class constructor, although doing so will reset a static variable’s value to its initial value each time a new object of the class is instantiated Instead, to assign an initial value to a static data member, you add a global statement to the implementation file using the syntax type class::variable=value; Initializing a static data member at the global level ensures that it is only initialized when a program first executes—not each time you instantiate a new object 26
  27. 27. Static Data MembersFigure 7-39 contains an example of the Stocks class, with the iStockCount static data member Statements in the constructor and destructor increment and decrement the iStockCount variable each time a new Stocks object is created or destroyed Figure 7-40 shows the program’s output 27
  28. 28. Static Data MembersYou can refer to a static data member by appending its name and the member selection operator to any instantiated object of the same class, using syntax such as stockPick.iStockCount By using the class name and the scope resolution operator instead of any instantiated object of the class, you clearly identify the data member as static Figure 7-41 in the text shows an example of the Stocks class program with the dPortfolioValue static data member The dPortfolioValue static data member is assigned an initial value of 0 (zero) in the implementation file 28
  29. 29. Static Data Members To add to the Estimator class a static data member that stores the combined total of each customer’s estimate, follow the instructions listed on pages 403 and 404 of the textbook 29
  30. 30. Static Member FunctionsStatic member functions are useful for accessing static data members Like static data members, they can be accessed independently of any individual class objects This is useful when you need to retrieve the contents of a static data member that is declared as private Static member functions are somewhat limited because they can only access other static class members or functions and variables located outside of the class 30
  31. 31. Static Member Functions You declare a static member function similar to the way you declare a static data member-- by preceding the function declaration in the interface file with the static keyword You do not include the static keyword in the function definition in the implementation file Like static data members, you need to call a static member function’s name only from inside another member function of the same class 31
  32. 32. Static Member Functions You can execute static member functions even if no object of a class is instantiated One use of static member functions is to access private static data members To add to the Estimator class a static member function that returns the value of the static lCombinedCost data member, use the steps on pages 405 and 406 of the textbook 32
  33. 33. Constant Objects If you have any type of variable in a program that does not change, you should always use the const keyword to declare the variable as a constant Constants are an important aspect of good programming technique because they prevent clients (or you) from modifying data that should not change Because objects are also variables, they too can be declared as constants 33
  34. 34. Constant Objects As with other types of data, you only declare an object as constant if it does not change Constant data members in a class cannot be assigned values using a standard assignment statement within the body of a member function You must use an initialization list to assign initial values to these types of data members There is an example of this code shown on page 407 of the textbook 34
  35. 35. Constant Objects Another good programming technique is to always use the const keyword to declare get functions that do not modify data members as constant functions The const keyword makes your programs more reliable by ensuring that functions that are not supposed to modify data cannot modify data To define the Estimator class’s get functions as constant, perform the procedures listed on page 408 of the textbook 35
  36. 36. Summary The default constructor is the constructor that does not include any parameters and that is called for any declared objects of its class to which you do not pass arguments Initialization lists, or member initialization lists, are another way of assigning initial values to a class’s data members A copy constructor is a special constructor that is called when a new object is instantiated from an old object 36
  37. 37. Summary Operator overloading refers to the creation of multiple versions of C++ operators that perform special tasks required by the class in which an overloaded operator function is defined When you declare a class member to be static, only one copy of that class member is created during a program’s execution, regardless of how many objects of the class you instantiate 37