350 likes | 365 Views
Today's lecture covers user-defined manipulators in C++ and the concept of static variables, including examples of manipulation and usage.
E N D
Introduction to Programming Lecture 38
Today’s Lecture • User Define Manipulator • Static key word
Example int i = 10 ; cout << setwidth ( 7 ) << i <<endl ;
Definition ostream & manipulatorName ( ostream & os ) { return os << userDefinedManipulator ; }
User Defined Manipulators A Short Example • // Tab • ostream & tab ( ostream & output ) • { • return output << '\t' ; • } • // bell • ostream & bell ( ostream & output ) • { • return output << '\a' ; • } • // Takes the cursr to next line • ostream & endLine ( ostream & output ) • { • return output << '\n' << flush ; • } • void main ( ) • { • cout << "Virtual " << tab << "University" << bell << endLine ; // Use of Mainpulator • }
Static Are variables which exist for a certain amount of time which is longer than an ordinary automatic variable.
Example int i ; void myfunction ( void ) { int i ; for ( i = 0 ; i < 10 ; i ++ ) cout << i << endl ; }
static int i = 0 ; //Initialization ......... i = 0 ; //Ordinary Assignment Statement
Example void f ( void ) { static int i = 0 ; i ++ ; cout << “Inside function f value of i : ” << i << endl ; } main ( ) { int j ; for ( j = 0 ; j < 10 ; j ++ ) ; f ( ) ; }
Example class Truck { char a ; public : Truck ( char c ) { a = c ; cout << "Inside constructor for object " << a << endl ; } ~ Truck ( ) { cout << "Inside destructor for object " << a << endl ; } } ;
Example Truck a ( 'A' ) ; main ( ) { Truck b ( 'B' ) ; f ( ) ; g ( ) ; cout << “Function g has been called " << endl ; }
Example void f ( ) { Truck c ( 'C' ) ; } void g ( ) { static Truck g ( 'G' ) ; }
Example Output Inside constructor for object A Inside constructor for object B Inside constructor for object C Inside destructor for object C Inside constructor for object G function g has been called Inside destructor for object B Inside destructor for object G Inside destructor for object A
Example class Truck { public : int wheels ; int seats ; } ; main ( ) { Truck A ; A.seats ; }
Example class SavingsAccount { private : char name [ 30 ] ; float accountNumber ; float currentBalance ; static float profitRate ; // ... public : SavingsAccount ( ) ; //... } ;
SavingsAccount A ; A.profitRate ; // bad usage
Example class Student { public : static int howMany ; Student ( ) { howMany ++ ; } ~ Student( ) { howMany -- ; } void displayHowMany ( ) { cout << "Number of students are " << howMany ; } } ; int Student :: howMany = 0 ;
What we covered today • Parameter Less Manipulation • Static Data