Download presentation
Presentation is loading. Please wait.
1
Class and Object Cont’d
Static Data Members Static Member Functions Arrays of Objects (1) Objects as Function Arguments (3) Friendly Functions (2) Returning Objects (4)
2
STATIC DATA MEMBERS Initialized to zero when the first object of its class is created. One copy, shared by all objects. Visible only within the class. Example: 100 200 300 3 a b c count
3
#include <iostream.h>
class item { static int count; // count is STATIC int number; public: void getdata( int a ) { number = a; count++; } void getcount( void ) { cout << "count = " << count << "\n"; }; int item :: count; // count DEFINED as static data member main( ) { item a, b, c; // count is initialized to zero a.getcount( ); b.getcount( ); c.getcount( ); // display count a.getdata(100); b.getdata(200); c.getdata( 300 ); cout << "after reading data" << "\n"; a.getcount(); b.getcount(); c.getcount(); // display count
4
Static Member Function
Have access to only other static members (functions or variables) declared in the same class. Can be called using the class name (instead of its objects) as follows : class-name :: function-name;
5
#include <iostream.h>
class test { static int count; // count is STATIC int code; public:void setcode( void ) { code = count++; }; void showcode( void ) { cout << "code = " << code << "\n"; static void showcount( void ) // STATIC MEMBER FUNCTION { cout << "count = " << count << "\n"; int test :: count; // count DEFINED as static data member main( ) { test a, b; // count is initialized to zero a.setcode( ); b.setcode( ); test :: showcount(); test c; c.setcode(); a.showcode(); b.showcode(); c.showcode(); }
6
// program array of objects
#include <iostream.h> class benda { int kode; public:void setkode( int x ) { kode = x; }; void showkode( void ) { cout << “kode = " << kode << "\n"; main( ) { benda array_benda[3]; cout <<“Inisialisasi data…” <<“\n”; for(int i=0; i<3; i++) array_benda[i].setkode( i*10 ); for(i=0; i<3; i++) array_benda[i].showkode(); }
7
// objects as function argument
#include <iostream.h> class time { int hours; int minutes; public: void gettime(int h, int m) { hours = h; minutes = m; } void puttime(void) { cout << hours << " hours & " << minutes << " minutes \n"; } void sum(time, time); // objects are arguments }; void time :: sum(time t1, time t2) { minutes = t1.minutes + t2.minutes; hours = minutes / 60; minutes = minutes % 60; hours = hours + t1.hours + t2.hours; main( ) { time T1, T2, T3; T1.gettime(2, 45); T2.gettime(3, 30); T3.sum(T1, T2); cout << "T1 = "; T1.puttime(); cout << "T2 = "; T2.puttime(); cout << "T3 = "; T3.puttime();
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.