270 likes | 372 Views
Object Oriented Programming Dr. Alon Schclar. Based on slides by Elhanan Borenstein (now at Stanford http://www.stanford.edu/~ebo/). Lecture #2. Agenda. Classes & Objects Definition & Motivation Data Members Data Members vs. Function variables Private & Public Permissions
E N D
Object OrientedProgrammingDr. Alon Schclar Based on slides by Elhanan Borenstein (now at Stanford http://www.stanford.edu/~ebo/) Lecture #2
Agenda • Classes & Objects • Definition & Motivation • Data Members • Data Members vs. Function variables • Private & Public Permissions • Objects as Data Members • Pointers to Objects • Methods (Member Functions) • Member Functions vs. Global Functions • The “this” Pointer • Working with Files • Object Size and Local Objects
Classes & Objects Introduction • A class represents a data entity. • Classes could (and should) be regards as new types, just like the fundamental types: int, float, char, etc. • Each class defines: • Data Members - The data we want to store. • Methods (member functions) - The operations that could be applied to this data. • The application will define/create various Objects according to the available classes. It will then be able to assign values to its data members and activate its methods.
Classes & Objects Definition • A class is defined (declared) and used as follows: class MyClass{ [private:] variables (data members) … functions (methods) … public: variables (data members) … functions (methods) …}; void main(){ // define objects of type // class_name MyClass MyObject1; MyClass MyObject2; // call a member function MyObject1.func1(…); // assign value to data members MyObject1.Index = 12;}
Classes & Objects Example – CPoint • The class CPoint represents a point in the 2D space… class CPoint { int m_x , m_y; public: void Init() { m_x = 0; m_y = 0; } void Set(int ax, int ay) { m_x = ax; m_y = ay; } void Print() { cout<<"x = "<<m_x<<", y = "<<m_y<<endl; } }; #include <iostream.h> void main() { CPoint p1, p2; p1.Init(); p2.Set(4,6); p1.Print(); p2.Print(); } How to merge Init and Set?
Data Members Data Members vs. Function variables • Member functions “know” all the data members of the same object. • When activating a member function of an object, it can operate on the data member of that object. • Equivalent to sending the “struct” part to the function • Short parameter lists • Unlike local variables (that “lives” only until the function terminates) the data members are alive as long as the object is alive.
Data Members Private and Public Permissions • Members (data & functions) can have either a public or a private permission. • Public members can be accessed at any point in the code (if you have access to the object they are in). • Private members can be accessed only by member functions of that class. • The permissions can be set using the keywords “public:” and “private:” and will apply until the next occurrence of public:/private: .
Data Members Private and Public Permissions • The default permission of a class is private. • Permissions can be altered as many time as we want. • Conventions: • Default: Private(functions,variables), Public(functions,variables) • Public(functions,variables), Private(functions,variables) • Varibles(public/private), Functions(public/private) • Functions(public/private) , Varibles(public/private)
Data Members Why Private? • Prohibitingdirect access to the data members by a programmer using the class. • But why? (encapsulation, modularity, safety) • Example : CPoint (p. 40) • Rule: • There should be a good reason to define data member as public. • There is usually no such reason!!!! • So, how can we access private data members? • Get and Set functions… • ByRef return value… (not recommended)
Classes vs. Structs Formal • A struct is a class whose default permission is public (reminder: the default permission in a class is private). • Thus: • struct { private: … } is equivalent to class { …} • class { public: …} is equivalent to struct { … } In Practice • The use of structs in C++ is scarce. • They will be mainly used to define data collections with no methods (very similar to their usage in C).
Objects as Data Members • Data members can also be: • Objects • Array of objects Example: CTriangle (p. 41) • Pointers to objects
Objects as Function arguments • Note: When sending an object as a function argument: • It is preferred to send it ByRef (efficiency). • If the function should not change the object – add “const”. (We actually did the same in C, sending pointers to structures instead of the struct itself)
Pointers to Objects • In an analogue manner to the definition of pointers to fundamental data type in C (i.e. int *pIndex), we can define pointers to objects (i.e. CPoint *pMyPoint). • Important: Pointers to objects do not necessarily represent real objects. We should: • Assign it with a pointer to an existing object, or… • allocate a new object to this pointer. • Example: pmain (p. 44) • What about memory allocation and freeing of data members? • Constructors and destructors • Mutual pointers • Example: Gardens and Gardeners (p.42)
Methods (Member Functions) Member Functions vs. Global Functions • Member functions (methods) • represents the services each class offers. • operate on the data members of the object • can be access only through the object. • encapsulation • modularity • Global functions will be used for general purpose operations that can not be assigned to any specific class. • examples? • Naming conventions: function and variable
Methods (Member Functions) Using the pointer “this” • Inside a member function we operate on a specificobject (the one which activated the function), although, we do not know its name. • Unlike a global function – access via the variable name • Wht to do when we need to refer to the whole object? • Sending the object to a different function… • Returning the object as return value… • Use the pointer “this”, • Reserved word • Points to the operating object. • Example: this (p.45)
Methods (Member Functions) External Function Implementation • Functions that are being implemented inside the class definition are automatically defined as inline functions. • Loops or otherwise complicated functions are notappropriate. • Inline function should be used only for simple functions • Most functions should be implemented externally. • Within the class definition we shall only include their prototypes. • To indicate that a function implementation is a member function, we can use the scope resolution operator“::”
Methods (Member Functions) Working with Multiple Files • Most classes will be implemented in two files: • header file (.h) – class definition: data members and prototypes. • code file (.cpp) – a collection of function implantations. main.cpp cpoint.h cpoint.cpp #include “cpoint.h” #include “ctriangle.h” … void main() { CPoint P1; … } class CPoint { int m_x , m_y; public: void Init(); bool Set(int ax, int ay); void Print(); int GetX() { return m_x; } int GetY() { return m_y; } }; #include “cpoint.h” void CPoint::Init() { … } bool CPoint::Set(int ax, int ay) { … } … class CPoint { int m_x , m_y; public: void Init(); bool Set(int ax, int ay); void Print(); int GetX() { return m_x; } int GetY() { return m_y; } }; #include “cpoint.h” void CPoint::Init() { … } bool CPoint::Set(int ax, int ay) { … } … class CPoint { int m_x , m_y; public: void Init(); bool Set(int ax, int ay); void Print(); int GetX() { return m_x; } int GetY() { return m_y; } }; #include “cpoint.h” void CPoint::Init() { … } bool CPoint::Set(int ax, int ay) { … } …
A Few Notes about Objects Object Size • The object size is the sum of all sizes of its datamembers. (member functions do not effect the object size). Why? • The operator sizeof can be applied to both classes and objects: sizeof(CPoint) sizeof(int + int) sizeof(P1) the same sizeof(CTriangle) sizeof(CPoint + CPoint + CPoint ) sizeof(T1) the same
A Few Notes about Objects Local Object • Local objects (which were defined within a function), die when the function terminates (just like a local variable). • Local objects can be used though as ByVal return-values (since a copy of it will be created on the stack). Global Objects • Objects which are defined externally to the main function will be global objects (just like global variables). • Created before main • deleted only after the main function terminates.
Strings in C • Should be used in EX2 • Not intuitive • strcpy instead of = • May overwrite after target • strcmp instead of == • strcat instead of + • C++ : the class string • Fixes all the above and more …
C++ string class • Replaces C character arrays • How to declare ? • string str; // Empty string • string str(s); OR String str = s • Initializes to s(string or char array) • str will contain a copy of s • string str (charArr, n); • Initializes str to contain a copy of the first n characters of charArr Based on slides from http://www.cs.niu.edu/~abyrnes/
C++ string class – stdin i/o • Reading a string from stdin • cin >> str; • Skips leading whitespace and reads nonwhite characters up to the next white space. • getline(cin, str); • Gets characters from cin into str until a newline character OR end of file is reached • getline(cin, str, delimiter); • From cin into str until the delimiter is found (not stored in str) OR end of file is reached • Printing a string • cout << str; Based on slides from http://www.cs.niu.edu/~abyrnes/
C++ string class • Assignment • str = val; • Assigns a copy of val to str. • Concatenation • str + val; OR val + str; • concatenates str and value, • str += value; • Appends a copy of value to str. • val may be a string, char array, or char Based on slides from http://www.cs.niu.edu/~abyrnes/
C++ string class • Relational Operators • str < s str <= s • str > s str >= s • str == s str != s • s may be a string or char array • Content access • str[p] or str.at(p) • returns a reference to the character stored in strat position p Based on slides from http://www.cs.niu.edu/~abyrnes/
C++ string class – common methods • str.length() • returns the number of characters in str • str.substr(p, n) • returns a copy of a sub-string n characters long, starting at position p • str.c_str() • converts the string object str to a null terminated char arrayreturns: const char * Based on slides from http://www.cs.niu.edu/~abyrnes/
Exercise • A dynamic array- A special case of container • Snake • All based on examples by Amir Kirsh • http://www2.mta.ac.il/~amirk/cpp/programs/ • The presented examples contain minor changes • Strings