2.29k likes | 2.39k Views
IT College. Introduction to Object Oriented Methodology. Classes Fundamentals.
E N D
IT College Introduction to Object Oriented Methodology
Classes Fundamentals • Class defines data type, which can be used to create objects. A class is created using the keyword Class. When you define a class, you will define both the data and the code that operates upon that data. That is, a class will have both code and data members.
Classes Fundamentals This create the class queue. Class queue { int q[100]; int sloc, rloc; public: void init ( ); void qput ( int i ); int qget ( ); };
Classes Fundamentals • A class can contain private as well as public members. By default, all items defined in a class are private. This means that they can only be accessed by other members of the class, and not by any other part of your program. We can also define private functions, which can only be called by other members of the class. • To make parts of a class public you must declare them after the public keyword. All variables or functions defined after the public specifies are accessible by all other functions in you program. Typically, your program will access the private parts of a class through its public functions.
Classes Fundamentals • The functions init( ), qput ( ) and qget ( ) are called member functions. A member functions has access to the private parts of the class of which it is a member. • Once you have defined a class, you can create an object of that type using the class name. A class name becomes a new data type specifier. Or after the class definition. • EX: queue Q1, Q2; • When an object of a class is created, it will have its own copy of the data members that comprise the class.
Classes Fundamentals • To implement a function that is a member of a class, you must tell the compiler which class the function belongs to by qualifying the function name with the class name. For example, void queue::qput ( int i ) { } • We use this way to tell the compiler that qput is part from queue class. • Member functions can only be invoked relative to an object. To call a member functions from a part of your program that is not part of the class, you must use the object's name and the dot operator. For example, this calls init( ) for object ob1. • Queue ob1, ob2; • Ob1. init ( );
An Instance Programmatically Class queue { int q[100]; int sloc, rloc; Public: void init(); void qput(int i); int qget(); };
An Instance Programmatically //initialize the queue. Void queue::init() { rloc=sloc=0; } //put an integer into the queue Void queue::qput(int i) { if (sloc==100){ cout<<“queue is full”; } sloc++; q[sloc]=i; }
An Instance Programmatically //get an integer from the queue. Int queue::qget() { if (rloc==sloc){ cout<<“queue underflow”; return 0; } rloc++; return q[rloc]; } main() { queue a,b; a.init(); b.init(); a.qput(10); b.qput(19); a.qput(20); b.qput(1); cout<<“contents of queue a:”; cout <<a.qget()<<“ “; cout<<a.qget<<“\n”; cout<<“contents of queue b:”; cout <<b.qget()<<“ “; cout<<b.qget<<“\n”; return 0; }
A Closer Look at Class Member Access Class myclass { int a; //private data public: int b; //public data void setab (int I); //public functions int geta(); void reset(); }; void myclass::setab(int i) { a=i; // refer directly to a and b here b=i*i; }
A Closer Look at Class Member Access int myclass::geta() { return a; //refer directly to a here. } void myclass::reset() { //call setab() directly setab(0); //the object is already known }
A Closer Look at Class Member Access main() { myclass ob; ob.setab(5); // set ob.a and ob.b cout<<“ob after setab(5): “; cout <<ob.geta()<<‘ ‘; cout<<ob.b; // may access b because it is public cout<<“\n”; ob.b=20; // again, may access b because it is public cout<<“ob after ob.b=20: “; cout<<ob.geta()<<“ “; cout<<ob.b; cout<<“\n”; }
A Closer Look at Class Member Access ob.reset(); cout<<“ob after ob.reset(): “; cout<<ob.geta()<<“ “; cout<<ob.b; cout<<“\n”; return 0; } The program above produces the following output: Ob after setab(5): 5 25 Ob after ob.b=20: 5 20 Ob after ob.reset(): 0 0
Constructors and Destructors • A constructor is a function that is called when an object is created. • A constructor function is special function that is a member of the class and has the same name as that class. • An object’s constructor is called when the object is created. • For global objects, the constructor is called when the program begins execution, prior to the call to main(). • For local objects, the constructor is called each time the object declaration is encountered. • A destructor function is the function that is called when an object is destroyed.
Constructors and Destructors • Local objects are created when their block is entered, and destroyed when the block is left. • Global objects are destroyed when the program terminates. • There are many reasons why a destructor function may be needed. For example, an object may need to deallocate memory that it had previously allocated. • The destructor has the same name as the constructor, but preceded by a ~. Like constructors, destructors do not have return type.
Constructors and Destructors class queue { int q[100]; int sloc, rloc; public: queue(); //constructor ~queue(); //destructor void qput(int i); int qget(); }; queue::queue() { sloc=rloc=0; cout<<“queue initialized\n”; } queue::~queue() { cout<<“queue destroyed\n”; }
Constructors and Destructors //put an integer into the queue Void queue::qput(int i) { if (sloc==100){ cout<<“queue is full”; } sloc++; q[sloc]=i; } //get an integer from the queue. Int queue::qget() { if (rloc==sloc){ cout<<“queue underflow”; return 0; } rloc++; return q[rloc]; }
Constructors and Destructors main() { queue a,b;// create two queue objects a.qput(10); b.qput(19); a.qput(20); b.qput(1); cout<<“contents of queue a:”; cout <<a.qget()<<“ “; cout<<a.qget<<“\n”; cout<<“contents of queue b:”; cout <<b.qget()<<“ “; cout<<b.qget<<“\n”; return 0; }
Constructors and Destructors This program displays the following output: Queue initialized Queue initialized 10 20 19 1 Queue destroyed Queue destroyed
#include < iostream.h > Class test { int a , b; public: void init (); void put ( int i ); int sum (); }; Void test::init() { a = b = 0; } Void test::put ( int i ) { a = b = i; } Int test::sum ( ) { return a + b; }
Int main ( ) { Test a , b ; a.init (); b.init(); a.put ( 10 ); b.put ( 20 ); cout << a.sum ( ); // 20 cout << b.sum ( ); // 40 return 0; }
# include < iostream.h > Class myclass { int a; public: int b; void setab( int i ); int geta ( ); void reset ( ); }; Void myclass::setab( int i ) { a = i ; b = i * i; } Int myclass :: geta ( ) { return a; }
Void myclass :: reset ( ) { setab ( 0 ); } int main ( ) { myclass ob; ob.setab ( 5 ); cout << ob.geta ( ) << ob.b; // 5 25 ob.b=20; cout<< ob.geta ( ) << ob.b; // 5 20 ob.reset ( ); cout<< ob.geta ( )<< ob.b; // 0 0 returen 0; }
Constructors and Destructors Constructor • It is a function that is called when an object is created. • Initialize class members. • Cannot return values and can be overloaded; • Can take arguments. • Have the same name as the class. Destructor • it is a function that is called when an object is destroyed. Name is tilde ( ~ ) followed by the class name ( i.e., ~Time ). • Can not take arguments. • Return no value. • One destructor per class ( No overloading allowed )
#include < iostream.h > Class Test { int a; int who; Public: Test ( int id ); ~Test(); void put ( int i ); int get (); }; Test :: Test ( int id ) { a = 0; who =id; cout<<“Create “<<who;} Test::~Test ( ) { cout << “destory “<< who; } Void Test::put ( int i ) { a = i ; } Int Test :: get () { returen a; }
Int main ( ) { queue a ( 1 ) , b ( 2 ); a.put ( 10 ); b.put ( 20 ); cout << a.get () << b.get (); returen 0; } Output:: Create 1 Create 2 • 20 Destroy 2 Destroy 1
#include < iostream.h > Class test { int a , b; public: void init (); void put ( int i ); int sum (); }; Void test::init() { a = b = 0; } Void test::put ( int i ) { a = b = i; } Int test::sum ( ) { return a + b; }
Int main ( ) { Test a , b ; a.init (); b.init(); a.put ( 10 ); b.put ( 20 ); cout << a.sum ( ); // 20 cout << b.sum ( ); // 40 return 0; }
# include < iostream.h > Class myclass { int a; public: int b; void setab( int i ); int geta ( ); void reset ( ); }; Void myclass::setab( int i ) { a = i ; b = i * i; } Int myclass :: geta ( ) { return a; }
Parameterized Constructors • A constructor function can have parameters. Thos allows you to give member variables program-defined initial values when an object is created. class queue { int q[100]; int sloc, rloc; int who; // holds the queue’s ID number. public: queue(int id); //constructor ~queue(); //destructor void qput(int i); int qget(); };
Parameterized Constructors queue::queue(int id) { sloc=rloc=0; who=id; cout<<“queue”<<who<<“initialized\n”; } queue::~queue() { cout<<“queue”<<who<< “destroyed\n”; }
Parameterized Constructors //put an integer into the queue Void queue::qput(int i) { if (sloc==100){ cout<<“queue is full”; } sloc++; q[sloc]=i; } //get an integer from the queue. Int queue::qget() { if (rloc==sloc){ cout<<“queue underflow”; return 0; } rloc++; return q[rloc]; }
Parameterized Constructors main() { queue a(1),b(2);// create two queue objects a.qput(10); b.qput(19); a.qput(20); b.qput(1); cout <<a.qget()<<“ “; cout<<a.qget<<“ ”; cout <<b.qget()<<“ “; cout<<b.qget<<“\n”; return 0; }
Parameterized Constructors This program produces the following output: Queue 1 initialized Queue 2 initialized 10 20 19 1 Queue 2 destroyed Queue 1 destroyed
Inline Functions • An inline function is a function that is expanded in line at the point at which it is invoked, instead of actually being called. There are two ways to create an inline function. The first is to use the inline modifier. For example, to create an inline function called f which returns an int and takes no parameters. You declared it like this: inline int f() { //…….. } • The reason for inline function is efficiency.
Inline Functions • Every time a function is called, a series of instructions must be executed, both to set up the function call, including pushing any arguments onto the stack, and to return from the function. In some cases, many CPU cycles are used to perform these procedures. However, when a function is expanded in line, no such overhead exists, and the overall speed of your program will increase. • Where the inline function is large, the overall size of your program will also increase. For this reason, the best inline functions are those that are very small.
Inline Functions class c1 { int i; //private by default. public: int get_i(); void put_i(int j); }; inline int c1::get_i() { return i; } inline void c1::put_i(int j) { i=j; } main() { c1 s; s.put_i(10) cout<<s.get_i(); return 0; }
Inline Functions • If you compile this version of the program, save its object code, and then compile it again with the inline specifier removed, you will see the inline version is several bytes smaller. • Inline is a request not a command, that the compiler generate inline code. • Some compilers will not generate inline code if a function contains a loop, a switch, or a goto. • You cannot have inline recursive functions. • Inline functions that contain static variables are frequenrtly disallowed.
Creating Inline Functions Inside a Class • Any function that is defined inside a class definition is automatically made into an inline function. It is not necessary to precede its declaration with the keyword inline. class c1 { int i; Public: //automatic inline functions. int get_i() {return i;} void put_i(int j) {i=j;} }; main() { c1 s; s.put_i(10); cout<<s.get_i(); return 0; }
Arrays of Objects • You can create arrays of objects in the same way that you create arrays of any other data types. #include <iostream.h> enum disp_type {mono, cga, ega, vga}; class display { int colors; //number of colors enum disp_type dt; // display type Public: void set_colors(int num) {colors=num;} int get_colors() {return colors;} void set_type(enum disp_type t) {dt=t;} enum disp_type get_type() {return dt;} }; char names [4][5] = {“mono”, “cga”, “ega”, “vga”};
Arrays of Objects main() { display monitors[3]; int i; monitors[0].set_type(mono); monitors[0].set_colors(1); monitors[1].set_type(cga); monitors[1].set_colors(4); monitors[2].set_type(vga); monitors[2].set_colors(16); for(i=0;i<3;i++) { cout<<names[monitors[i].get_type()]<<“ “; cout<<“has “<<monitors[i].get_colors(); cout<<“ colors”<<“\n”; } return 0; }
Arrays of Objects This program produces the following output: mono has 1 colors cga has 4 colors vga has 16 colors
Pointers to Objects #include <iostream.h> class p_example { int num; public: void set_num(int val) {num=val;} void show_num(); }; void p_example::show_num() { cout<<num<<“\n”; }
Pointers to Objects main() { p_example ob[2], *p; ob[0].set_num(10);// access objects directly ob[1].set_num(20); p=&ob[0];// obtain pointer to first element p->show_num();// show value of ob[0] using pointer p++;// advance to next object; p->show_num();// show value of ob[1] using pointer p--; //retreat to previous object p->show_num(); return 0; } The output from this program is 10, 20, 10
Friend Functions • It is possible to allow a non-member function access to the private members of a class by declaring it as a friend of the class. • To make a function a friend of a class, you include its prototype in the public section of a class declaration and begin it with the friend keyword.
Friend Functions Class myclass { int a, b; Public: myclass(int i, int j) {a=i;b=j;} friend int sum(myclass x); }; // note: sum() is not a member function of any class int sum(myclass x) { //Because sum() is a friend of myclass, it can directly access a and b; return x.a+x.b; } main() { myclass n(3,4); cout<<sum(n); return 0; }
Friend Functions • A function may be a friend of more than one class. const int IDLE =0; const int INUSE=1; class c2; //forward reference class c1 { int status; // idle if off, inuse if on screen public: void set_status(int state); friend int idle(c1 a, c2 b); };
Friend Functions class c2 { int status; // idle if off, inuse if on screen public: void set_status(int state); friend int idle(c1 a, c2 b); }; void c1::set_status(int state) { status=state; }
Friend Functions void c2::set_status(int state) { status=state; } int idle(c1 a, c2 b) { if(a.status || b.status) return 0; else return 1; }
Friend Functions main() { c1 x; c2 y; x.set_status(IDLE); y.set_status(IDLE); if(idle(x,y)) cout<<“screen can be used\n”; else cout << “Pop-up In use\n”; x.set_status(INUSE); if(idle(x,y)) cout <<“Screen can be used\n”; else cout <<“Pop-up in use\n”; return 0; }