1 / 113

Understanding Classes in Programming: Encapsulation and Member Functions

Learn about the concepts of encapsulation in classes, member functions, private and public data, and the role of constructors and destructors in object-oriented programming.

pardee
Download Presentation

Understanding Classes in Programming: Encapsulation and Member Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. The Queue class • //this class implements a Queue class Queue{ int q[100];//an array of integers int sloc, rloc; //start location and rear location public: void init(); void qput(int i); int qget(); };

  2. Classes continued • So as we know a class contains both private and public members • So q, sloc and rloc are private, this means that they can be accessed only by other members of the Queue class e.g. the functions of this class and NOT by other parts of the program in which this class has been written. • The functions are also referred to as methods • This hiding is known as ENCAPSULATION

  3. Classes continued • Typically we place the functions in the public interface and the data in the private interface, but we can declare private functions if we wanted to. • The functions init(), qput() and qget() are called member functions of the class, note the parentheses () to denote that they are functions.

  4. Classes continued • Keep in mind that an object forms a bond between the functions and the data i.e. an object will have associated with it both data and functions. • A member function has access to the private parts of the class of which it is a member. Thus init(), qput() and qget() have access to q, sloc and rloc. • Once a class is declared we can create objects (i.e.variables) of the type class as follows: • Queue q1, q2 • This will declare two objects q1 and q2 of type Queue

  5. Declaration of classes class class_name{ private: data and functions public: public data and functions } object_list; //recall we can do this with structs i.e. the //object_list part

  6. Coding the functions void Queue::qput(int I//i added to the queue) { if (sloc==100){ cout << “Queue is full ” << endl; return; } sloc++; //increment sloc q[sloc] = i; }//this will put the value i at position q[sloc] in the //array of integers

  7. :: The scope resolution operator • Note the use of the :: • This is known as the scope resolution operator, which means that the function name to the right of the two colons is in the scope of the class name to the left of the colon • In short it means that the function (or method) belongs to the class or the method is in the scope of the class.

  8. The :: operator again • The :: is called the scope resolution operator. Essentially it tells the compiler that this version of qput belongs to the Queue class • Or put differently :: states that qput() is in Queue’s scope • Member functions can only be invoked relative to an object. • To call a member function from part of your program that is not part of the class one must use the object name and the dot operator, as we did with structs e.g. • Queue ob1,ob2; • ob1.init();

  9. The dot operator continued • The invocation ob1.init() causes init() to operate on ob1’s copy of the data. • Keep in mind that ob1 and ob2 are separate objects. • Now look at queue*.cpp and discuss

  10. A closer look at class member access • How to access class members is a cause of considerable confusion for programmers. • So for this reason we will look at this in more detail. • Let us look at Myclass.cpp

  11. Member function access continued • Lets look at setab(). • As it is a member function it can refer to a and b directly without explicit reference to an object i.e. without the dot operator • Second note that a is private and b is public, so b can be accessed by code outside Myclass. • So main() assigns a value of 20 to b • reset() is a function of Myclass so has access to members of the class without the use of dot operator. In this case it calls setab()

  12. Constructors and Destructors • It is very common for some part of an object to require initialisation before it can be used. • Recall the Queue class previously, before the Queue could be used the variables rloc and sloc were set to zero. This was done using the function init() //short for initialisation • Automatic initialisation is done using the constructor • Lets look at the Queue2.cpp. (no constructor)

  13. The use of a Constructor Queue::Queue() //note no return type { rloc=0; sloc=0; cout << "Queue initialised " << endl; } Here the constructor writes to the screen Queue initialised, this is not common practice. An objects constructor is called at inception i.e. when the object is created

  14. The Destructor • The complement to the constructor is the destructor. • In many cases an object will need to perform some action or series of actions when it is destroyed. • Reasons for destructor: object may need to deallocate memory that it had previously allocated

  15. The Destructor • In C++ the destructor is the function that handles deactivation. • The destructor has the same name as the constructor and thus the class, but it is preceded by the tilda ~. • Like constructors they do not have a return type. • The Queue class does not require a destructor but we will include one for illustration, see Queue3.cpp

  16. Parameterised Constructors • A constructor can have parameters thus we can have different signatures for the constructor. • This allows you to give member variables values at inception • Lets look at Queue4.cpp • Here we will see a constructor with more than one signature, this is known as POLYMORPHISM analogous to OVERLOADING

  17. Public and Private • If you look closely at the previous definition of our classes you may note one or two things • class definition is similar to struct definition • In fact C++ treats structs as classes where by default all members are public • class definition contains function prototypes • the operations are bound tightly to the data • class functions know about class data so you do not need to pass class data to functions as arguments

  18. The Private and public interfaces • class definition has a line with a label public: this tells the compiler which parts of the class are visible to other things (clients) e.g. main() and other functions • class members are by default are private. • That is private members functions and data which are hidden to all. • private data and functions are only visible to an object itself.

  19. Class Data Manipulation • The principle of Information Hiding is the key for Object Oriented Programming. • Access to data is tightly controlled via public interface functions • “Setters” to set data members • SetHeight(3); • “Getters” to obtain values of data members • y = myTime.Write(); Here myTime is an object of type Time, say.

  20. Built in operators • int, char, float, double have built in operators • + * / % etc • classes do not have them • like structs they have . (dot) and = • You have to define and implement your own operators (i.e. methods) • It is possible but perhaps beyond this course to redefine the built in operators to work on YOUR class.

  21. Specification an Implementation Like Abstract Data Types (ADT’s) there are two parts to classes • the specification – where one declares the class • implement the function definitions i.e. to code the functions. This is not crucial but it is how it is discussed in many text books.

  22. Key Points so far • Shows practical elements of object oriented programming . • Information hiding • Via class syntax • Loose coupling • Classes are very self contained • There only interaction with other parts of a project is via its public interface which can be strictly monitored • They are independent of other parts of your program • They can therefore be developed and tested in isolation • They result in more robust code • They are easy to reuse/ adapt/extend/ • They are ideal for team programming • For large project they are more productive • They are ideal for large programs

  23. Constructors and Destructors • Constructors guarantee initialisation and are called when an object is created • Usually we want to set up an object with certain values for its data. • Special member function called a constructor will “construct” or initialise any instance of our class exactly how we want to. • The constructor is called at the time of object instantiation! i.e. when we create an object of that class.

  24. Revised class declaration class Time { public: void setTime (int hours, int minutes, int seconds); void print24hour(); void print12hour(); Time(int initHrs, int intMins, int initSecs) //constructor Time (); // overloaded constructor ~Time(); //destructor private: int hour; int minute; int second; };

  25. Define constructor Time::Time() { cout << “Setting the time” << endl; hrs=0; mins=0; secs = 0; } //Note the constructor has the same name as the class itself //constructors have NO RETURN TYPE not even void.

  26. Purpose of constructor and destructor • They ensure that objects created are properly initialised • They ensure that they are properly destroyed • So they can sort out any garbage collection, for example memory de-allocation. • Once this is done properly then class can be used more reliably.

  27. Summary • A class can be used to implement an ADT • A class specifies members - the data and operations (methods) • Information hiding is a central idea to classes • class members are private by default so if you forget to include an interface they will be private by default • Interface functions are explicitly labelled as public • Classes provide automatic initialisation through constructors • Classes provide a place for garbage collection through destructors. • Creation of an object is achieved via a declaration statement.

  28. Structures versus Classes • On the surface structures and classes are virtually identical, so why introduce the class? • Answer is rooted in C. A C struct is valid in C++. C has no concept of private or public all members are public in structs • In C++ members are private by default as we are trying to achieve encapsulation • So to be compatible with C a new keyword was added. • A struct is a class. • Look at displaydatestruct.cpp

  29. Arrays of objects • We can create arrays of objects just as we had arrays of structs previously Look at display.cpp

  30. Pointers to Objects • As you know you can access a structure directly, or through a pointer. In like fashion you can access an object either directly or by using a pointer • Recall that a pointer stores an address • To access an element of an object when using the actual object itself use the dot operator. When using the pointer we use the -> //pronounced arrow link (dereferencing operator) • See example p_Example.cpp

  31. Extending classes • Here we derive one class from another • The derived class is called the child class or the subclass • The class derived from is called the superclass or the parent class • If one imagines set theory the parent class is a sub set of the child class • Inheritance is known as a “is a” relationship

  32. Extending in OO programming • Analogy to set theory Child class Parent class

  33. instantiate object A of type ExtTime enum ZoneType {EST, CST, MST, PST, EDT, CDT,MDT} class ExtTime:public Time { public: void Set(int hours, int minutes, int seconds); void print24hour(); void print12hour(); ExtTime(int int Hours, int initMins, int initSecs, ZoneType initZone); ExtTime(); private: ZoneType zone; }; int main() { ExtTime A; return 0; }

  34. Further Ideas • C++ and other object oriented languages take things further. • For example, suppose we had a problem modelling vehicles • We need an Abstract Data Type (ADT) for a vehicle • That is a Vehicle class, written by the user for the user

  35. Vehicle ADT DATA: position speed heading Operations Accelerate Break Turn DisplayInfo

  36. Suppose we want to model a bus • A bus “is a” kind of vehicle • It would be good if we could make use of our vehicle implementation and extend it to include bus specific data members and operations

  37. Bus ADT bus is a kind of vehicle plus DATA: nPassengers Operations: board passenger alight passenger DisplayInfo

  38. This can be done using Inheritance • A class can inherit data and operations from another class • It can also redefine operations (this is called polymorphism) so that they work with the new class • e.g DisplayInfo will need to be adapted to display bus specific information as well as vehicle information.

  39. This can be done using Inheritance • This process of inheritance further extends the programmers ability to reuse and extend code already written. • These principles lie at the heart of OOP which are • Information hiding • Inheritance and polymorphism

  40. Object Oriented Programming • Identify what the goals are for a problem • Identifying the objects that make up a problem • Identifying how the objects in a problem interact with each other in order to satisfy the goals • Specifying ADTs that describe the objects and operations needed for the problem

  41. JAVA • The second module at Oxford in JAVA takes these concepts further • JAVA is a “pure” object oriented language with a distinct C++ flavoured Syntax • It is pure in the sense you cannot program in Java without classes. • Everything in Java is a class

  42. Inheritance in C++ Introduction: Modern object-oriented (OO) languages provide three capabilities: encapsulation inheritance polymorphism which can improve the design, structure and reusability of code. Here, we will explore how the object-oriented (OO) programming paradigm known as inheritancecan be used in C++. All coded examples are available in lecture.

  43. Is inheritance important to C++? • Inheritance is what separates abstract data type (ADT) programming from OO programming. • It is one the three paradigms that OO programming has which we refer to when discussing an OO programming language. • Encapsulation • Polymorphism • Inheritance

  44. When would I use inheritance? • As a specification device. • Human beings abstract things on two dimensions: part-of and kind-of. • A Ford Focus is-a-kind-of-a Car, and a Ford Focus has-a Engine, Tires, etc. • The part-of hierarchy has been a part of software since the ADT style became relevant; inheritance adds "the other" major dimension of decomposition.

  45. How do you express inheritance in C++? • By the : public syntax: •  class Car : public Vehicle { public:...//code for class Car  }; • Here the Car class inherits publicly from the Vehicle class

  46. Describing this • We state the above relationship in several ways: • Car is "a kind of a" Vehicle • Car is "derived from" Vehicle • Car is "a specialized" Vehicle • Car is a "subclass" of Vehicle • Car is a "derived class" of Vehicle • Vehicle is the "base class" of Car • Vehicle is the "superclass" of Car (this not as common in the C++ community)

  47. How do you express "private inheritance"? • When you use : private instead of : public. E.g., •  class Food : private Bar { public:... }; • Let us look at PublicProtected1.cpp, PublicProtected2.cpp and PublicProtected3.cpp • And explain

  48. Inheritance types

  49. What is the difference between public, private, and protected? • A member (either data member or member function) declared in a private section of a class can only be accessed by member functions and friends of that class • A member (either data member or member function) declared in a protected section of a class can only be accessed by member functions and friends of that class, and by member functions and friends of derived classes • A member (either data member or member function) declared in a public section of a class can be accessed by anyone

  50. Why can't my derived class access private things from my base class? • To protect you from future changes to the base class. • Derived classes do not get access to private members of a base class. • This effectively "seals off" the derived class from any changes made to the private members of the base class.

More Related