classes
DESCRIPTION
Classes. classes and objects from object-oriented programming point of view class declaration class class_name{ data members … methods (member functions) … }. Classes. member access specifiers private public protected information hiding - PowerPoint PPT PresentationTRANSCRIPT
1
Classes classes and objects
- from object-oriented programming point of view
class declarationclass class_name{
data members …
methods (member functions) …
}
2
Classes
member access specifiers- private
- public
- protected information hiding
- private (and protected) can be used to hide the data members and methods
- public is used to expose the data members and methods to the outside
3
information hiding
class Person {
public: boxer
void setAge(unsigned n);
unsigned getAge( );
private:
unsigned age;
}
Person boxer, student; student
boxer.setAge(27);
student.setAge(18);
cout << boxer.age; // Error: age is private data
cout << boxer.getAge( ); // o.k.
priviate: age public: setAge( )getAge( )
27
priviate: age public: setAge( )getAge( )
18
4
Classes
class scope of private members- only can be accessed by its own class
methods (functions)
define class methods- defined inside the class
- inline declaration
- good for small codes
- defined outside the class
5
define class methods
defined inside the classclass Person {
public:
void setAge( unsigned n ) { age = n; }
unsigned getAge( ){ return age; }
private:
unsigned age;
};
6
define class methods
defined outside the class
class Person {
public:
void setAge( unsigned n );
unsigned getAge( );
private:
unsigned age;
};
void Person::setAge( unsigned n ){
age = n;
}
unsigned Person::getAge( ) {
return age;
}
7
using classes in a program
#include <iostream>using namespace std;class Person {public: void setAge( unsigned n ) { age = n; } unsigned getAge( ) { return age; }private: unsigned age;};
int main() { Person p; Person stooges[ 3 ]; p.setAge( 12 ); stooges[ 0 ].setAge( 45 ); stooges[ 1 ].setAge( 46 ); stooges[ 2 ].setAge( 44 ); cout << p.getAge() << '\n'; for ( int i = 0; i < 3; i++ ) cout <<stooges[ i ].getAge( ) << '\n'; return 0;}
8
classes
class and struct- both can be used to create classes
class- all members default to private if not specified
struct- all members default to public if not specified
9
class and struct
class C { int x; // private by defaultpublic: void setX( int X); // public}
struct C { void setX( int X); // public by defaultprivate: int x; // private}
10
application: stack class
stack- a Last In First Out (LIFO) data structure
- contains:- an array for storing data, an index variable
- basic operations- push: add an element to the stack
- pop: extract an element from the stack
- IsFull (IsEmpty): test whether the stack is full (empty)
- dump: print out the contain of the stack
- init: initialize the stack
11
stack Initialize: arr[MaxStack]
MaxStack – 1 MaxStack top 3 2 public: 1 push( ) 0 pop( ) IsEmpty() IsFull() Dump()
. . .100
-1
12
stack push(100);
MaxStack – 1 MaxStack
top
3
2
1
0
(note: the sequence of pushing data )
100
100
0
13
stack push(100); push(30);
MaxStack – 1 MaxStack
top
3
2
1
0
(note: the sequence of pushing data )
30100
100
1
14
stack push(100); push(30); push (88);
MaxStack – 1 MaxStack
top
3
2
1
0
(note: the sequence of pushing data )
8830
100
100
2
15
stack push(100); push(30); push (88); push(307);
MaxStack – 1 MaxStack
top
3
2
1
0
(note: the sequence of pushing data )
3078830
100
100
3
16
stack
x = pop( );
MaxStack – 1 MaxStack
top
3
2
1
0
(note: the pop sequence, Last In First Out)
8830100
100
2
17
stack
x = pop( ); y = pop( );
MaxStack – 1 MaxStack
top
3
2
1
0
(note: the pop sequence, Last In First Out)
30100
100
1
18
stack class defintion
class Stack {public:enum {MaxStack =100};void init(){top =-1; dummy_val = -9999;}void push(int n ){ if (isFull()){ errMsg("Full stack.Can ’t
push."); return; } arr [++top ]=n;}
int pop(){
if (isEmpty()){
errMsg("Empty stack.Popping dummy value.");
return dummy_val;
}
return arr [top--];
}
19
stack class definition
bool isEmpty(){return top <0;}
bool isFull(){
return top >=MaxStack -1;}
void dump(){
cout <<"Stack contents,top to bottom:\n";
for (int i =top;i>=0;i--)
cout <<’\t ’<<arr [i ]<<’\n ’;
}
private:
void errMsg(const char*msg )
{ cerr <<"\n***Stack operation
failure:"<<msg <<’\n ’; }
int top;
int arr [MaxStack ];
int dummy_val;
};
20
create a Stack object
Stack s1; // create an object s1
s1 arr[MaxStack]
MaxStack – 1 MaxStack
top s1.init( );
dummy_val
3 public:
2 init( )
1 push(int)
0 pop( )
dump( ) …
. . .100
-1
21
Stack objects
#include <iostream>
using namespace std;
class Stack {
// stack definition
. . .
}
int main( ) {
Stack s1;
s1.init( ):
s1.push(100);
s1.push(30);
s1.push(88);
s1.push(307);
s1.dump( ); // 100 30 88 307
s1.pop( );
s1.pop( );
s1.push(55);
s1.dump( ); // 100 30 55
return 0;
}
22
object reference
passing and returning objects by reference- cp. by value
- save time and space
- need to declare static if return by reference
const method- cannot change any values of data members
of it’s object
23
object reference
#include <iostream>
using namespace std;
class C {
public:
void set( int n ) { num = n; }
int get( ) const { return num; }
private:
int num;
};
void f( C& );
C& g( );
int main( ) {
C c1, c2;
f( c1 ); // pass by reference
c2 = g( ); // return by reference
cout << c2.get( ) << '\n';
return 0;
}
24
object reference
void f( C& c ) {
c.set( -999 );
cout << c.get() << '\n';
}
C& g( ) {
static C c3; // static, not auto
c3.set( 123 );
return c3;
}
output:
-999
123
25
constructors and destructors
constructor- a method with the same name as it’s class
- automatically executed while the object is created
- may be overloaded, among them only one constructor is executed
destructor- with the same name plus a ~ sing
- automatically executed while the object is destroyed
26
constructors
class Person {public:Person( ) { name = "Unknown";
}Person( const string& n );Person( const char* n );void setName( const string& n );void setName( const char* n );const string& getName( ) const;private:string name;};
Person::Person( const string& n ) {name = n;}Person::Person( const char* n ) {name = n;}…int main( ) {Person anonymous;Person jc(“J. Coltrane”); …}
27
dynamic allocation of objects
#include <cstdlib> // for malloc and calloc
class Emp {
public: elvis
Emp() { /*...*/ }
Emp( const char* name ) { /*...*/ } cher
//...
};
int main() {
Emp* elvis = new Emp(); // default
Emp* cher = new Emp( "Cher" ); // convert
Emp object
instance
Empobject
instance
28
dynamic allocation of objects
Emp* lotsOfEmps = new Emp[ 1000 ]; // default
Emp* foo = malloc( sizeof( Emp ) ); // no constructor
//...
} Emp object array
lotsOfEmps
foo…
Empobject
29
destructor
#include <iostream>#include <string>using namespace std;class C {public:// default constructorC( ) { name = "anonymous"; cout << name << "
constructing.\n";}
// parameterized constructorC( const char* n ) { name = n; cout << name << "
constructing.\n";}~C( ) { cout << name << "destructing.\
n"; }private:string name;};
30
destructor
int main() { output:
C c0( "hortense" ); { C c1; C c2( "foo" ); cout << '\n'; } // c1 and c2 destructors calledC* ptr = new C( ); delete ptr;return 0; // c0 destructor called}
hortense constructing anonymous constructing. foo constructing foo destructing. anonymous destructing.
anonymous constructing. anonymous destructing. hortense destructing.
31
pointer to objects
class C {public:void m() { /*...*/ }};
void f( C* ); // pass a pointerint main() {C c1;c1.m(); // objectf( &c1 ); // address of
object//...}
void f( C* p ) {p->m(); //
pointer to C object}
32
pointer to objectsclass C {public:void m() { /*...*/ }};
void f( C& ); // pass by reference
int main() {C c1;c1.m(); // objectf( c1 );//...}
void f( C& c ) {c.m(); // object
reference}
33
pointer constant “this”
this- default constant pointer variable points to the
object itself
- no need to declare
- an object: note:
“this” is the object
itselfthis …
34
this
class C {
public:
C( ) { this->x = 0;} // same as: x=0;
private:
int x;
}
35
this (example: copy file)
…
void File::copy(File& dest) {
if (this == &dest) // cannot copy file to itself
return;
// otherwise, copy the file to dest
…
}