730 likes | 944 Vues
Chap.7 C++. 서울대학교 컴퓨터공학부 객체지향시스템연구실 snu oopsla lab 교수 김 형 주. Contents. Introduction Object Orientation in C++ Pros and Cons of C++ Class Definition Inheritance in C++ Overloading/Overriding, Dynamic Binding Templates Streams in C++. Introduction.
E N D
Chap.7 C++ 서울대학교 컴퓨터공학부 객체지향시스템연구실 snu oopsla lab 교수 김 형 주 OOPSLA LAB. SNU
Contents • Introduction • Object Orientation in C++ • Pros and Cons of C++ • Class Definition • Inheritance in C++ • Overloading/Overriding, Dynamic Binding • Templates • Streams in C++ OOPSLA LAB. SNU
Introduction • 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 OOPSLA LAB. SNU
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 OOPSLA LAB. SNU
Advantages • 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 operations • Popularity and multi-vendor support • GNU, Borland, Microsoft, Watcom • Standard platform for window-based application OOPSLA LAB. SNU
Disadvantages • 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 OOPSLA LAB. SNU
Class Construct • Grammar rules class <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 *) }; OOPSLA LAB. SNU
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(); OOPSLA LAB. SNU
Member Function • Methods of the class class Person { int Age; public: Set(int a); Print() {printf(“age = %d\n”,Age); } } Person::Set(int a) { Age = a > 0 ? a : 0; } OOPSLA LAB. SNU
The “this” pointer: Pseudovariable • Pseudovariable thiscontains 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); OOPSLA LAB. SNU
Constructors and Destructors • Constructor initializes an instance of an object during creation • Destructor does clean-up operations right before the object destruction class A //private member storage allocations initialization object a public: constructor storage deallocation client destructor A a; // ..... :a’s life is terminated OOPSLA LAB. SNU
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’); • . . . • } OOPSLA LAB. SNU
Several constructors can be specified for a given class • class Furniture • { int NumOfLegs; • Char *Fabric; • public: • Furniture(char *Style); • Furniture(int num_legs, char fabric); • }; OOPSLA LAB. SNU
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”); • . . . • } OOPSLA LAB. SNU
When are Constructors and Destructors Called?** The beginning and end points of each variable’s life time OOPSLA LAB. SNU
Friend 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. OOPSLA LAB. SNU
class Person { int Age; char Sex; public: friend void aging(Person *p, int years); }; void aging(Person *p, int Years) { p->Age+=Years; } // C++ Statement Aging(&Jonn, 1); OOPSLA LAB. SNU
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; } . . . . OOPSLA LAB. SNU
class X { . . . }; class Y { . . . Public: . . . . friend class X; . . . }; • All private members of class Y are available to the methods of class X OOPSLA LAB. SNU
Struct Construct • A struct declaration is equivalent to a class declaration with no private section class X struct X { { public: ... equivalent to ... }; }; OOPSLA LAB. SNU
struct Person { int Age; char Sex; print() printf("age = %d sex= %c",Age,Sex); }; In C++ : Person Bob; In C : struct Person Bob; OOPSLA LAB. SNU
Union Construct • The union construct also has been extended to support multi method definitions union 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 OOPSLA LAB. SNU
x, y share the same memory location and appropriate constructors for each field • // declares a “Share” union construct with integer value • Share first(1); • // declares a “Share” union construct as string • Share second("nxvnzx"); OOPSLA LAB. SNU
Another clear way of “Union” declaration! 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 OOPSLA LAB. SNU
Inline 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 OOPSLA LAB. SNU
Declaring Inline Functions • Member functions defined within a class • Keyword inlinecan be specified with the function declaration inline 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 OOPSLA LAB. SNU
Static 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 OOPSLA LAB. SNU
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 OOPSLA LAB. SNU
Inheritance in C++ • General form of derived class declaration class <derived-class-name> : [public | private] <base-class-name> { <derived-class-member> }; • A derived class inherits instance variable and methods from a base class OOPSLA LAB. SNU
“IS-A” relationship exists between derived class and base class base class (superclass) Person inherit all members derived class (subclass) Student OOPSLA LAB. SNU
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 • classare inherited • as public members • of the derived class OOPSLA LAB. SNU
Private 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 OOPSLA LAB. SNU
No “Public” keyword! Class PrivatePerson : Person { public : person::Name; } class PrivatePerson { Private: char Address[20]; int Age; public: char Name[10]; }; PrivateStudent Mary; . . . . strcpy(Mary.Name, ”Mary Joe"); Mary.Age = 21; // error OOPSLA LAB. SNU
Inheritance through Struct (1) class <derived-class-name>: public <base-class-name> { public : <public_member_decl> }; // through Struct Construct struct <derived-class-name>: <base-class-name> { <public_member_decl> }; OOPSLA LAB. SNU
Inheritance in Struct (2) • “Struct GraduateStudent” has access to all public members from both Student and Person classes Struct GraduatedStudent : Student { AdvisorName : char[20]; } Remember that “Class Student: public Person” OOPSLA LAB. SNU
Extending 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 OOPSLA LAB. SNU
Inheritance 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 OOPSLA LAB. SNU
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; } }; OOPSLA LAB. SNU
Protected 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; // Error Ay.I = 2; // Error OOPSLA LAB. SNU
Virtual 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 OOPSLA LAB. SNU
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(); } OOPSLA LAB. SNU
void Display(Person *APerson) { APerson ->Print(); printf(”\n"); } Student Joe("Joe", 21, 12343); Person Wanda("Wanda", 22); Display(&Joe); // call student::print Display(&Wanda); // call person::print // Output Student ID = 12343, Name= "Joe”, age = 21 Name = "Wanda" , age = 22 OOPSLA LAB. SNU
Multiple Inheritance • Syntax rule class <new-derived-class> : [virtual] [public | private | protected] <base-class> {, [virtual] [public | private | protected] <base-class2>...} { ... }; OOPSLA LAB. SNU
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; } } OOPSLA LAB. SNU
Multiple Inheritance and Construction/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 } }; OOPSLA LAB. SNU
Virtual 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 Staff Student Only one copy of Person member WorkStudy OOPSLA LAB. SNU
name name name office ID office Person name // Virtual Base Class Student Person Staff name name vbase Student office Staff name vbase WorkStudy ID name WorkStudy vbase name ID Two Copy of Person Member ID office OOPSLA LAB. SNU
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; }}; OOPSLA LAB. SNU
Advantages 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 OOPSLA LAB. SNU
Function 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 OOPSLA LAB. SNU