c classes a quick introduction n.
Skip this Video
Loading SlideShow in 5 Seconds..
C++ Classes – A Quick Introduction PowerPoint Presentation
Download Presentation
C++ Classes – A Quick Introduction

C++ Classes – A Quick Introduction

182 Vues Download Presentation
Télécharger la présentation

C++ Classes – A Quick Introduction

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. C++ Classes – A Quick Introduction • Many programming languages support OOP: SMALLTALK, CommonLisp Object System, C++ • Advantages of C++: • C++ provides a well-designed set of mechanisms to fully support OOP needs • C++ is an extension of the already popular and standardized ANSI C.

  2. What is OOP? • The central idea is to build program using software objects • Object = data + operations = data members + methods

  3. Traditional programming deals with bytes, variables, arrays, pointers, and other programming artifacts that are difficult to relate to the problem at hand. • Traditional programming focuses mainly on the step-by-step procedures, called algorithms to achieve the desired tasks. • In this sense, traditional programming is called procedure-oriented programming

  4. The breakthrough concept of OOP is the attachment of program procedures to data items. This concept changes the traditional segregation between data and programs.

  5. Class Declaration • Like declare structure in C++ • Ex • Class myClass{ int x; char y; }; //create an object of myClass myClass myObject;

  6. A typical class has several data members • To Provide internal representation • Ex class intCell { public: intCell ( ) {storedValue=0;} intCell (int initialValue) {storedValue=initialValue;} int read ( ) (return storedValue;} void write (int x) (storedValue=x;} private: int storedValue; } • Explain intCell class

  7. Public, private, protected • There are three statuses for class members • public: can be accessed anywhere • private: can be accessed by methods of the same class, or by friend functions to the class • protected: cannot be accessed outside the class, but protected members allow inheritance

  8. Declaration format class myDog { public: myDog(); barkDog(); playDog(); protected: ownDog(); Private: char name[31]; char owner[31]; };

  9. Ex. Class stack { private: char items[100]; int top; public: void init(); void push(char); char pop(); int empty(); int full(); };

  10. void stack::init(){ top=-1; } void stack::push(char c){ if (full()) return; item[++top]=c; } void stack::pop(){ if (empty()) return ‘$’; //’$’ indicates empty return item[top--]; }

  11. int stack::full(){ if (top+1==100) return 1; else return 0; } int stack::empty(){ if (top==-1) return -1; else return 0; }

  12. Constructor • A constructor is a special class method that can automatically initialize all the data members in a class. That is, whenever an object is created, the constructor is automatically invoked to do the initialization • Advantages of having a constructor?

  13. Ex. class stack{ private: char item[100]; int top; public: stack() {top=-1;} //constructor void push(char); void pop(); … }; //create a stack object Stack myStack; //initialization is automatic

  14. A constructor’s name is the class’ name • A class may have more than one constructor • The default constructor is the one without parameters • Ex. class myColor{ private: float red, green, blue; public: myColor(){red=green=blue=0;} myColor(float, float, float); } myColor::myColor(float r, float g, float b){ red=r; green=g; blue=b; } myColor dog; myColor cat(1.0, 5.5, 6.4);

  15. Default Parameters class stack{ private: char item[100]; int top; public: stack(int n=0) {top=n;} //constructor void push(char); void pop(); … }; //create stack objects Stack myStack; //initialization using default parameter Stack yourStack(100); //initialization using non-default parameter

  16. Explicit Constructors • Ex class intCell { public: explicit intCell (int initialValue=0) {storedValue=initialValue;} int read ( ) {return storedValue;} void write (int x) {storedValue=x;} private: int storedValue; } • C++ has lenient rules allowing implicit type conversion for single parameter constructor, which is good in some cases but very bad at other cases. • Explicit constructor of single parameter is designed to prevent this kind of implicit type conversion. IntCell test; Test=10; //error. If the constructor is not explicit, then it is okay

  17. Constructor Initialization: Three Styles • Style one: use assignment class A{ private: int intA; float floatA; public: A(int a, float b){ intA=a; floatA=b; } };

  18. Style two: initialize in the header, body empty class B{ private: int intB; float floatB; public: B(int a, float b): intB(a), floatB(b){ } };

  19. Style three: both header and body class C{ private: int intC; float floatC; public: C(int a, float b): intC(a){ floatC=b } };

  20. How to choose a style? • If the data member is cosnt or object in the other class, then it must be initialized in the header.

  21. Copy ConstructorA class C constructor can take a C reference parameter • Ex. class myColor{ private: float red, green, blue; public: myColor(){red=green=blue=0;} myColor(myColor &); }; myColor::myColor(myColor& t) {;;; }

  22. The purpose of a copy constructor is to initialize a new object using an existing object • Ex. myColor dog (1.2, 6.4, 10.8); myColor cat(dog); • Since the main job of a constructor is to initialize data members of a class, the constructor needs to dynamically allocate storage and then initialize the storage when a data member is a pointer type.

  23. Ex. class C{ private: char *text; public: C(); … }; C::C(){ text=new char[40]; strcpy(text, “I like data structures.”); }

  24. Destructor • A destructor is a special class method that destroys (or reallocate) memory storage allocated for a class object • Destructor name: ~class_name

  25. Ex. class C{ private: char *text; … public: C(); ~C(){delete[] text;} … }; C::C(){ text=new char[40]; strcpy(text, “I like data structures.”); }

  26. A destructor has no type, never returns a value, and have no arguments. • A class has only one destructor.

  27. Operator Overloading-Redefine an Operator • Ex. class string{ private: char *str; public: string& operator=(const string&); string& operator+(const string) const; string(char*); }; string& string::operator+(const string s) const{ char * tmp; tmp=new char[strlen(str)+strlen(s.str)+1]; strcpy(tmp,str); strcat(tmp, s.str); return string(tmp); }

  28. In the above case, we overload + operator. In general, we need to use “operator” to overload an operator like +. • “const string s” in the argument list means s cannot be changed. • “const” after the argument list means the object invoking the + operator cannot be changed.

  29. C++ supports any operator overloading except the following operators: . //member selection .* //member dereference :: //scope resolution ?: //conditional operator sizeof //size in bytes • Operator overloading is not easy • Note: Java does not support general operator overloading except a few cases such as + for string concatenation

  30. Operator vs. Function • An operator is in essence a function • Ex.s? • An overloaded operator is a user-defined function that retains the convenience of the operator syntax. • In other words, we may live without operator overloading at all, or just a little overloading.

  31. definition of the overloaded assignment operator string& string::operator=(const string s){ //check whether object assigned to itself if (this !=&s){ delete[] str; str=new char[strlen(s.str)+1]; strcpy(str, s.str); } return *this; } • Note this.

  32. Another Ex. class intCell{ public: intCell(){storedValue=0;} intCell(int a){storedValue=a;} int read(){return storedValue;} void write(int x){storedValue=x;} //overload assignment operator const intCell& operator=(cont intCell& rhs); private: int storedValue; }; //definition of the overloaded = const intCell& intCell::operator=(const intCell& rhs){ if (this !=&rhs) storedValue=rhs.storedValue; return *this; }

  33. Friend Functions • A friend function of a class (or a few classes) is a normal function except: • It must be specified using “friend” in the public domain of the class (or classes). • It can access the private and protected members of the class (or classes).

  34. Ex. class point; class pointStack{ private: point items[100]; … public: friend void printStack (pointStack); … }; class point{ private: int x, y; public: friend void printStack(pointStack); … }; void printStack(pointStack s){ for (int i=0; i<100; i++) cout<<s.items[i].x <<‘ ‘ <<s.items[i].y<<endl; }

  35. Generic Classes Using Templates • Purpose: Use templates to construct a class without specifying particular data types. When an object is created, we can specify data types in the object by specifying the desired types in the template. • Advantage: Support code reusability; promote code correctness

  36. Ex. A class using parameters for data types template<class typePara, int maxStack> class stack{ private: typePara items[maxStack]; int top; public: stack(); void push(typePara); typePara pop(); … };

  37. template <class typePara, int maxStack> stack<typePara, maxStack>::stack(){ top=-1; } template <class typePara, int maxStack> void stack<typePara, maxStack>::push(typePara x) { items[++top]=x; } template <class typePara, int maxStack> typePara stack<typePara, maxStack>::pop(){ return items[top--]; } … stack<int, 100> myStack; stack<char,1000> yourStack; stack<char*, 10000> herStack;

  38. Class parameters listed in the angle brackets must be either a type parameter or a function-style parameter. • A type parameter is preceded by the keyword “class”, it must be replaced by an actual type when a particular class is constructed. • A function-style parameter follows the same syntax as function parameters, and it must be replaced by a value when a particular class is constructed. • Templates are similar to parameterized macros and serve the same general purpose.

  39. Generic class such as templates provides yet another level of abstraction for programmers. Just as a class is an abstraction of a collection of object, so is a generic class an abstraction for a collection of classes. • Ex. GenericStack Class IntStack charStack stringStack

  40. Another Ex. //memoryCell template class interface //for simulate a memory cell template <class obj> class memoryCell{ public: memoryCell(const obj& initialValue=obj( )); const obj& read() const; void write(const obj& x); const memoryCell& operator=(cosnt memoryCell&); private: obj storedValue; }; template <class obj> const memoryCell<obj>& memoryCell<obj>::operator=(const memoryCell<obj>& rhs) { if (this != &rhs) storedValue=rhs.storedValue; return *this; } …

  41. Function Templates • A function template is not an actual function, but instead is a pattern for what could become a function.

  42. Ex. template <class typePara> const typePara& findMax(const vector<typePara>& a) { int maxIndex=0; for (int i=0; i<a.size(); i++) if (a[maxIndex]<a[i]) maxIndex=I; return a[maxIndex]; }

  43. Inheritance • The key point about inheritance is that we use existing classes to define new classes. The new classes will share some (or all) of members in the existing classes.

  44. Basic Concepts and Syntax • Base and derived classes Vehicle Class Base Class Ex. Car Class Derived Class

  45. Vehicle Class • Direct and indirect inheritance • Multiple inheritance Car Class Toyota 4Runner Class Accessory Class Vehicle Class Car Class Truck Class

  46. Member Accessibility • Private: Members may be accessed only by methods within its class or by friend functions • Protected: Members may be accessed only by methods within its certain class and within classes directly and indirectly derived from its own class, or by friend functions • Public: Members may be accessed globally

  47. Inheritance • In C++, all data members and methods of the base class, except for the constructors, the destructor, and the overloaded assignment operator, are always automatically included in the derived class.

  48. Syntax for deriving a class Class BaseClass{ … }; Class DerivedClass: accessSpecifier BaseClass{ … };

  49. Access Specifier: Control the type of access provided to the data members and methods inherited by the derived class from the base class. • Three types of specifiers: • private • protected • public

  50. Ex. class vehicle{ public: float mph, cost, weight; }; class car: public vehicle{ public: char maker[100], model[1000]; }; • You can add new members to the derived class. mph cost mph Vehicle car weight cost maker weight model