chap7.c++oopsla lab. snu1 chap.7 c++ 서울대학교 컴퓨터공학부...
TRANSCRIPT
CHAP7.C++ OOPSLA LAB. SNU 1
Chap.7 C++Chap.7 C++
서울대학교 컴퓨터공학부객체지향시스템연구실
snu oopsla lab
교수 김 형 주
OBJECT-ORIENTATION by Khoshafian and Abnous
CHAP7.C++ OOPSLA LAB. SNU 2
ContentsContents
Introduction Object Orientation in C++ Pros and Cons of C++ Class Definition Inheritance in C++ Overloading/Overriding, Dynamic Binding Templates Streams in C++
CHAP7.C++ OOPSLA LAB. SNU 3
IntroductionIntroduction
One of the most popular OO languages Bjarne Stroustrup (AT&T) in early 1980s
at first, as preprocessor for any C compiler currently there are many C++ compilers
B. Stroustrup, “The C++ Programming Language”,1986, 1st Edition B. Stroustrup, “The C++ Programming Language”,1991, 2nd Edition B. Stroustrup, “The C++ Programming Language”,1997, 3rd Edition
CHAP7.C++ OOPSLA LAB. SNU 4
Object Orientation in C++Object Orientation in C++
Abstract data types: struct, class Inheritance: single, multiple Object identity
Objects are referenced by name or address Pointer equality (address comparison) No shallow/deep equality
Overloading/overriding, parametric polymorphism, and dynamic binding polymorphism: through template dynamic binding: through virtual function
CHAP7.C++ OOPSLA LAB. SNU 5
AdvantagesAdvantages
True extension of the C language accept most standard C programs downward compatibility to C
Good performance (except virtual function) the earlier other OO languages had poor performance C++ compilers can generate well-optimized functions and op
erations
Popularity and multi-vendor support GNU, Borland, Microsoft, Watcom Standard platform for window-based application
CHAP7.C++ OOPSLA LAB. SNU 6
DisadvantagesDisadvantages
Hybrid object oriented language need not enforce information hiding inherit pointer-based low-level functions from C
Manual garbage collection the developer must manage memory at run time -> “dual
semantics” problem Only capable C++ programmers can exploit memory resources automatic garbage collection->run time cost
Lack of standard class hierarchy (until 1997) no predefined class hierarchy all major C++ vendors provide their own class library confusion & frustration: OWL, MFC
CHAP7.C++ OOPSLA LAB. SNU 7
Class ConstructClass Construct
Grammar rulesclass <class-name> {
private: <private-member-declaration>
(* member functions within this class, friend classes & functions *)
protected: <protected-member-declaration>
(* private + derived class’s member and friend functions *)
public: <public-member-declaration>
(* accessble from users of instances of this class *)
};
CHAP7.C++ OOPSLA LAB. SNU 8
Class Person {int age;char sex;
public :void Get(int *a, char *s) { *a = Age; *s = Sex; }void Set(int a, char s) { Age = a; Sex = s; }void printf()
{ printf(“age = %d sex = %c”, Age, Sex); } };
Person John;. . .John.Set(26, “m”);John.Print();
CHAP7.C++ OOPSLA LAB. SNU 9
Member FunctionMember Function
Methods of the classclass Person{
int Age;public:
Set(int a);Print()
{printf(“age = %d\n”,Age); }}
Person::Set(int a){ Age = a > 0 ? a : 0; }
CHAP7.C++ OOPSLA LAB. SNU 10
The “this” pointer: Pseudovariable The “this” pointer: Pseudovariable
•Pseudovariable this contains address of the instance for which the method was called.
class Person{ Person *Spouse;public:
GotMarriedTo(Person *p) { this ->Spouse = p; }
};
Person p1, p2;p1.GotMarriedTo(&p2);
CHAP7.C++ OOPSLA LAB. SNU 11
Constructors and DestructorsConstructors and Destructors
Constructor initializes an instance of an object during creation Destructor does clean-up operations right before the object destruction
//privatemember
public:
constructor
destructor
object a
class A
client
storage allocationsinitialization
storage deallocation
A a;// .....:a’s life is terminated
CHAP7.C++ OOPSLA LAB. SNU 12
class Person
{
int Age;
char Sex;
public:
Person(int AnAge,char SomeSex)
{ Age = AnAge; Sex = SomeSex;}
~Person() { ... }
};
f( ) { Person Bob(32,’m’);Person John = Person(26,’m’);. . .
}
CHAP7.C++ OOPSLA LAB. SNU 13
class Furniture{ int NumOfLegs;
Char *Fabric;public:
Furniture(char *Style);Furniture(int num_legs, char fab
ric);};
Several constructors can be specified for a given class
CHAP7.C++ OOPSLA LAB. SNU 14
Furniture::Furniture(char *style){
if(strcmp(style, “. . . . “)){
NumOfLegs = . . .strcpy(Fabric, . . . ._);
}. . .}Furniture::Furniture(int num_legs , char *fabric){ NumOfLegs = num_legs;
strcpy(Fabric, fabric);}
f( ) {Furniture chair(“Wooden Chair”);Furniture kids(3, “kid”);. . .
}
CHAP7.C++ OOPSLA LAB. SNU 15
When are Constructors and Destructors Called?When are Constructors and Destructors Called?
** The beginning and end points of each variable’s ** The beginning and end points of each variable’s life timelife time
Constructor Destructor
Automatic inside the block when the block isterminated
Static beginning of theprogram
during programtermination
Free store new operator delete operator
Member by constructor ofcontaining object
by destructor ofcontaining object
CHAP7.C++ OOPSLA LAB. SNU 16
Friend Functions and ClassesFriend Functions and Classes
Friend can have access to private instance variables and methods of a class
class Y
{ friend f(...);
public:
…...
friend class X;
......
};
Function f & class X can access all member and member functions of Y except the “this” pointer of Y.
Location of “friend” does not matter.
CHAP7.C++ OOPSLA LAB. SNU 17
class Person{
int Age;char Sex;
public: friend void aging(Person *p, int years);
};
void aging(Person *p, int Years){
p->Age+=Years;}
// C++ StatementAging(&Jonn, 1);
CHAP7.C++ OOPSLA LAB. SNU 18
class X{ int x1, x2;
int X(int , int );public:
friend void f1(X *x,Y *y);};class Y{ int y1, y2;
int Y(int ,int );public:
friend void f1(X *x,Y *y);};
void f1(X *x,Y *y){
y->y1 = x -> x1;y->y2 = x -> x2;
}. . . .
CHAP7.C++ OOPSLA LAB. SNU 19
class X{ . . . };
class Y{ . . . Public: . . . . friend class X; . . .};
All private members of class Y are available to the methods of class X
CHAP7.C++ OOPSLA LAB. SNU 20
Struct ConstructStruct Construct
A struct declaration is equivalent to a class declaration with no private section
class X struct X
{ {
public: ... equivalent to ...
}; };
CHAP7.C++ OOPSLA LAB. SNU 21
struct Person{
int Age;char Sex;print() printf("age = %d sex= %c",Age,Sex);
};
In C++ :Person Bob;
In C :struct Person Bob;
CHAP7.C++ OOPSLA LAB. SNU 22
Union ConstructUnion Construct The union construct also has been extended to
support multi method definitionsunion Share
{ int x;
char* y;
Share (int AnInt) { x = AnInt; }
Share (char *AString) { strcpy(y, AString);}
};
The two data fields X, Y share the same memory location
CHAP7.C++ OOPSLA LAB. SNU 23
// declares a “Share” union construct with integer value Share first(1); // declares a “Share” union construct as string Share second("nxvnzx");
x, y share the same memory location and appropriate constructors for each field
CHAP7.C++ OOPSLA LAB. SNU 24
class Share{ enum (INTG,STRG) tag;
union{
int x;char *y;
}public:
Share(int x) { tag=INTG; Share::x=x; } Share(char *y) { tag=STRG; strcpy(Share::y,y); }
};
scope resolution operator
Another clear way of “Union” declaration!
CHAP7.C++ OOPSLA LAB. SNU 25
Inline FunctionsInline Functions
C++ compiler replaces the function call with the body of the function
Advantages of an inline function over a #define macros argument type checking
When are inline functions used? Still compile-time code replacement only functions with few lines
CHAP7.C++ OOPSLA LAB. SNU 26
Declaring Inline FunctionsDeclaring Inline Functions
Member functions defined within a class Keyword inline can be specified with the function decl
arationinline int min(int x, int y)
{ return ((x > y) ? y : x); }
a = min(first, second); // is replaced as following
==> a ((first > second) ? second : first);
by compiler
CHAP7.C++ OOPSLA LAB. SNU 27
Static MembersStatic Members
A member or member function can be declared as static only one copy of each static member exists shared by all instances of the given class
Static members are used for information about the class and all instances integrity constraints similar to class instance variables or class methods in smalltalk
Static member must be initialized before its use
CHAP7.C++ OOPSLA LAB. SNU 28
class Person{ static int NoPersonObjects;
int Age;char Sex;
public:Person( int AnAge , char SomeSex){
NoPersonObjects++;. . . .
}~Person() { NoPersonObjects--; }
};
int Person::NoPersonObjects = 0;
Created and initialized before its use
CHAP7.C++ OOPSLA LAB. SNU 29
Inheritance in C++ Inheritance in C++
General form of derived class declarationclass <derived-class-name>
: [public | private] <base-class-name>
{
<derived-class-member>
};
A derived class inherits instance variable and methods from a base class
CHAP7.C++ OOPSLA LAB. SNU 30
“IS-A” relationship exists between derived class and base class
Person
Student
inheritall members
base class(superclass)
derived class(subclass)
CHAP7.C++ OOPSLA LAB. SNU 31
class Person {public:
char Name[10];char Address[20];int Age;
};class Student : public Person{public:
int StudentId;char CampusAddress[20];
};
Student Joe;. . .strcpy(Joe.Name, "Joe Jackson");strcpy(Joe.Address, "43 Main St. Sf, CA ");Joe.Age = 21;Joe.StudentId = 1011134;
Public members of the public base class are inherited as public members of the derived class
CHAP7.C++ OOPSLA LAB. SNU 32
Private Base ClassPrivate Base Class
Unless “public” keyword declaration inheritance, “public members” of the base class are inherited as `̀private members the instantiating clients of the derived class cannot access
these members
CHAP7.C++ OOPSLA LAB. SNU 33
class PrivatePerson {Private:
char Address[20];int Age;
public:char Name[10];
};
PrivateStudent Mary;. . . .strcpy(Mary.Name, ”Mary Joe");
Mary.Age = 21; // error
Class PrivatePerson : Person { public : person::Name;}
No “Public” keyword!
CHAP7.C++ OOPSLA LAB. SNU 34
class <derived-class-name>: public <base-class-name>{public :
<public_member_decl>};
struct <derived-class-name>: <base-class-name>{
<public_member_decl>};
// through Struct Construct
Inheritance through Struct (1) Inheritance through Struct (1)
CHAP7.C++ OOPSLA LAB. SNU 35
“Struct GraduateStudent” has access to all public members from both Student and Person classes
Struct GraduatedStudent : Student{
AdvisorName : char[20];}
Inheritance in Struct (2) Inheritance in Struct (2)
Remember that “Class Student: public Person”
CHAP7.C++ OOPSLA LAB. SNU 36
Extending a Class DeclarationExtending a Class Declaration
Derived classes can define additional members restrict or override existing members
When additional members may become needed, designer can take one of the followings redefinition of the base class declaration with new members declaration of newly derived classes with additional
members
CHAP7.C++ OOPSLA LAB. SNU 37
Inheritance and Constructors/ DestructorsInheritance and Constructors/ Destructors
The constructor of a base class is called before the constructor of a derived class
The destructor of a derived class is called before the destructor of a base class the destructor calling sequence is the reverse of the constructor
calling sequence
CHAP7.C++ OOPSLA LAB. SNU 38
class Person{public:
char Name[10];int Age;Person(char *AName, int AnAge);
};
class Student : public Person{public:
int StudentId;Student ( int AnId, char *AName, int AnAge)
: Person(AName , AnAge) { StudentId = AnId; }
};
CHAP7.C++ OOPSLA LAB. SNU 39
Protected MemberProtected Member
Protected members of the base class are inherited as private members by the derived classes
class X{protected :
int I;};class Y: public X{
Afunc() { I++};};
X AnX;Y Ay;. . .Anx.I = 1; // ErrorAy.I = 2; // Error
CHAP7.C++ OOPSLA LAB. SNU 40
Virtual FunctionsVirtual Functions
Provides dynamic binding through virtual functions Way of overriding of the same member function name Derived class may either inherit the virtual function or
define its own each subclass within the hierarchy can choose a different
implementation for this function
CHAP7.C++ OOPSLA LAB. SNU 41
class Person{ char Name(20);
int Age;public:
Person(char *AName, int AnAge);virtual void Print();
};
void Person::print(){ printf("Name = %s, age = %d ", Name, Age); }
class Student : public Person{ int StudentId;
public:Student(char *Name, int age , int id);void print();
}; void Student::Print(){ printf("Student ID = %d,", StudentId);
Person::Print();}
CHAP7.C++ OOPSLA LAB. SNU 42
void Display(Person *APerson){ APerson ->Print(); printf(”\n"); }
Student Joe("Joe", 21, 12343);Person Wanda("Wanda", 22);
Display(&Joe); // call student::printDisplay(&Wanda); // call person::print
// OutputStudent ID = 12343, Name= "Joe”, age = 21Name = "Wanda" , age = 22
CHAP7.C++ OOPSLA LAB. SNU 43
Multiple InheritanceMultiple Inheritance
Syntax ruleclass <new-derived-class> : [virtual]
[public | private | protected] <base-class>
{, [virtual] [public | private | protected] <base-class2>...}
{ ... };
CHAP7.C++ OOPSLA LAB. SNU 44
class A{
public :int a;
};class B{
public :int b;
};class C: public A, public B{
int c;f() { a = 5; b = 6; c = 8; }
}
CHAP7.C++ OOPSLA LAB. SNU 45
Multiple Inheritance and Multiple Inheritance and Construction/DestructionConstruction/Destruction
By default, the order of base class constructor execution will be the same as the declaration list
To override the order of construction -> manually!
class C : public A, public B
{ int c;
C(va, vb, vab) : B(vb), A(va) { c = vab }
};
CHAP7.C++ OOPSLA LAB. SNU 46
Virtual Base ClassVirtual Base Class Only one copy of the base class member will be created
for the derived class with keyword “virtual”class Person { ... }
class Student : virtual public Person { ... };
class Staff : virtual public Person { ... };
class WorkStudy : public Student, public Staff { ... };
Person
Student Staff
WorkStudyOnly one copy of Person member
CHAP7.C++ OOPSLA LAB. SNU 47
namename
Person
Student
namename
Staff
WorkStudy
namename
Person
Student
namename
IDID
namename
officeoffice
Staff
WorkStudy
namename
vbasevbase
IDID
namename
vbasevbase
officeoffice
namename
vbasevbase
IDID
officeofficeIDID
namename
officeoffice
// Virtual Base Class
Two Copy of Person Member
CHAP7.C++ OOPSLA LAB. SNU 48
Resolving Naming Conflicts(Ambiguity)Resolving Naming Conflicts(Ambiguity)
Inheriting multiple members with the same name ==> ambiguity
To resolve the ambiguity, member can be qualified by its class name manually
class Student { ... int ID; };
class Staff { ... int ID; };
class WorkStudy{.. GetID(){return ID;} } // error
class WorkStudy { .. GetID() { return Staff::ID; }};
CHAP7.C++ OOPSLA LAB. SNU 49
Advantages of OverloadingAdvantages of Overloading
Notational convenience Reducing the number of function names Extending the use of language operators for user-
defined types Provide an intuitive interface of functions and operators
CHAP7.C++ OOPSLA LAB. SNU 50
Function OverloadingFunction Overloading
Same function name can be applied with different types and quantities of arguments
Information to distinguish the same overloaded function name (used by the compiler) parameter types number of parameters
CHAP7.C++ OOPSLA LAB. SNU 51
int Doubler(int a){
return a * 2;}
char *Doubler(char *ch){
char *new = malloc ( 2 * strlen(ch));strcpy(new, ch);strcat(new, ch);return new;
}
CHAP7.C++ OOPSLA LAB. SNU 52
Dynamic Binding and OverloadingDynamic Binding and Overloading
Major differences of virtual function from the function overloading “virtual” are only within a class hierarchy “virtual functions”: the type and the number of arguments and
the resultant type are the same for all overloaded functions virtual functions bind only at run time
CHAP7.C++ OOPSLA LAB. SNU 53
Operator OverloadingOperator Overloading
Redefinition of the C++ operators for any user defined class
Keep in mind that the arity of an operator cannot be changed the precedence of an operator cannot be altered
Binary or unary operators can be defined friend function or ordinary function
all operands are specified as arguments member function
left operand is supplied automatically
CHAP7.C++ OOPSLA LAB. SNU 54
Table 7.1 C++ operators that can be overloaded
+ - * / % ^ & | ~ ! = < >
+= -= *= %= ^= &= |= -> ->*<< >> >>= <<= == != <= >= && || ++ --[] () new delete
CHAP7.C++ OOPSLA LAB. SNU 55
A + B
int
complex
C D+
‘+’ : add two integers
‘+’ : add two complexs
CHAP7.C++ OOPSLA LAB. SNU 56
class Complex { int Real;
int Imaginary;public:
Complex(int r1 = 0 , int ig = 0) { real = r1; Imaginary = ig;};Complex operator+ (Complex &Right);friend Complex operator- (Complex &Left,
Complex &Right);};
Ex) default parameter values Complex a; Complex b(2,3); Complex c(2); Complex d(,3);
default parameter values
CHAP7.C++ OOPSLA LAB. SNU 57
Complex Complex::operator+(Complex &Right){ Comple Res;
Res.Real = this -> Real + Right.Real;Res.Imaginary = this -> Imaginary + Right.Imaginary;return Res;
}Complex operator-(Complex &Left, Complex &Right){ Complex Res;
Res.Real = Left.Real - Right.Real;Res.Imaginary = Left.Imaginary - Right.Imaginary;Return Res;
}
CHAP7.C++ OOPSLA LAB. SNU 58
Main(){ Complex a(1,3); Complex b; Complex c = Complex(4,3); Complex d; b = a + c; d = a - b; b = a - 1; a = b - Complex(0,1);}
CHAP7.C++ OOPSLA LAB. SNU 59
Template in General (1)Template in General (1)
Parametric polymorphism Syntax for template definition
template <template-arguments> <declaration> Template arguments
parameterized type definition ex) class <id> just arguments such as a character string, constant expression, or
function name Declaration can be either a function or a class declaration
CHAP7.C++ OOPSLA LAB. SNU 60
Template in General (2)Template in General (2)
Without template, when we need stacks of int, char, some other class type, we should define stack class for each type
class stack_int class stack_char class stack_int
integerstack
charstack
Astack
<without template>
integerstack
charstack
Astack
Template stack class
type argument
<with template>
CHAP7.C++ OOPSLA LAB. SNU 61
Template FunctionTemplate Function
Generic function definition
template <class T>T max(T a, T b) { return (a > b) ? a : b; }
int first = 20, second = 40;int resi = max(first, second); . . . .double fd = 21.3, sd = 19.2;double resd = max(fd, sd);
Usage
CHAP7.C++ OOPSLA LAB. SNU 62
Template ClassTemplate Class
Template <class T>
class Stack {
T* theStack;
int top, size;
public:
stack (int s) { theStack = new T [size = s]; top = s; }
~stack() { delete[] theStack; }
void push(T a) { theStack[top++] = a; }
T pop() { return theStack[--top]; }
};
define template stack class
CHAP7.C++ OOPSLA LAB. SNU 63
stack<int> si(100); // define a stack of integer objectsint first, second;si.push(first);si.push(second);int res = si.pop();
Complex fc ,sc;stack<Complex> ComplexStack(100);ComplexStack.push(fc);ComplexStack.push(sc);Complex resc = ComplexStack.pop();
template <class T1>T1 stack<T1>::pop() {
return theStack[--top]; }
CHAP7.C++ OOPSLA LAB. SNU 64
Streams in C++Streams in C++
Library for performing I/O: <iostream.h> Streams perform serial I/O on formatted and unformatt
ed data Stream I/O operators can be overloaded with user-defi
ned types
CHAP7.C++ OOPSLA LAB. SNU 65
Streams in GeneralStreams in General
Standard streams in C++: cout, cin, cerr Syntax to output to a stream
<stream-name> << <data1> << <data2>...
#include <iostream.h>main(){
int AnIndex = 20;cout << “Value Of Index =” << AnIndex;
}
CHAP7.C++ OOPSLA LAB. SNU 66
Syntax to input to a stream<stream-name> >> <data1> >> <data2>...
Function to perform formatted outputchar* form(char *format,...);
#include <iostream.h>main(){
int index;cin >> index;cout << “Value of index =” << index;
}
cout << form(“Value of index = %d”, index);
CHAP7.C++ OOPSLA LAB. SNU 67
Stream StatesStream States
I/O stream has four states _good: previous I/O was successful and next input may succeed _eof: previous I/O was successful and the end of file has been rea
ched _fail: previous I/O was not successful _bad: previous I/O was not successful and data may be corrupted
rdstate() to examine the stream state cin >> ……………. While(cin.rdstate() != _bad) { cin >> … }
CHAP7.C++ OOPSLA LAB. SNU 68
istream Class Declarationistream Class Declaration
class istream {
public:
istream &operator>> (char*); istream &operator>> (char &); istream &operator>> (short &); istream &operator>> (int &); istream &operator>> (long &);istream &operator>> (float &); istream &operator>> (double &);stream_state rdstate();
... };
CHAP7.C++ OOPSLA LAB. SNU 69
ostream Class Declarationostream Class Declaration
class ostream{
public:ostream &operator<< (char *);ostream &operator<< (int);ostream &operator<< (long);ostream &operator<< (double);ostream &put(char);
... };
CHAP7.C++ OOPSLA LAB. SNU 70
Extending Stream I/O DefinitionExtending Stream I/O Definition
Overloading “<<“ for printing Person type object!!
ostream& operator<< (ostream& s, Person p){
return s << “(” << p.Name << “,” << p.Age << “)”; }
const OpenParen = ‘(‘;const CloseParen = ‘)’;const Comma = ‘,’ ;
CHAP7.C++ OOPSLA LAB. SNU 71
istream& operator>> (istream& s, Person &p){ char ch;
int i = 0; char name[20];int age = 0;name[0] = ‘/0’;s >> ch;if (ch == OpenParen){
s >> ch;while(isalpha(ch)){
name[i++] = ch; s >> ch;
}name[i] = ‘/0’;if(ch == Comma)
s >> age >> ch;if(ch != CloseParen)
s.clear(_fail);}else s.clear(_eof);if (s) p = Person(name, age);
return s;}
CHAP7.C++ OOPSLA LAB. SNU 72
#include <iostream.h>#include <person.hpp>main(){
Person Wanda(“Wanda”,22);Person Joe;cout << Wanda;cin >> Joe;cout << Joe;
}
input:(JOE, 32)
output:(Wanda , 22)(Joe, 32)
CHAP7.C++ OOPSLA LAB. SNU 73
SummarySummary
Good performance Low - level hardware abstraction exists Limited support for OO paradigm