Introduction to classes and objects.pdf

Full Transcript

Classes and Objects Learning Outcome A.1 Our discussion this time will focus on the core aspect of this subject. From time to time, I do believe that you have come across the term OOP. It is a very popular term in the programming world and with good reason. OOP stands for Object Oriented Programmin...

Classes and Objects Learning Outcome A.1 Our discussion this time will focus on the core aspect of this subject. From time to time, I do believe that you have come across the term OOP. It is a very popular term in the programming world and with good reason. OOP stands for Object Oriented Programming. This term has revolutionized modern day programming and helped make advances in the development and operation of very advanced systems from banking to airline industries and everything else in between. But beyond knowing what this acronym stands for, do you have any idea what it is all about? Well its quite simple. Almsost every problem that requires a programming solution, involve an entity or object. An object is really anything and everything that occupies space; either it be a book, a pen, your computer, mobile device or even you, yes you. These are real world objects that our programming solutions revolve around. What this means is that OOP, allows a programmer to aspects and characteristics of real life objects in their programs. This make solving programs easy as it becomes less imaginative and more practical for a programmer who is tasked with solving a particular program. For example, a program is required to help a spazashop owner manage their stock. Stock will include real life products, with characteristics that a programmer can quickly use without getting stuck. For instance, these products will obviously have a name, size, price and number or quantity available. These products are not imaginary, it is things the programmer can go to store, see and touch and this information can be directly inputted into the program he is developing very easily. From the example above, we can see the true benefit of using OOP; it simply allows the programmer to include real life objects and their characteristics in their programs/applications. And we already mentioned that an Object is anything and everything that occupies space. It should all make sense up to now. But now think about this; these objects have to come from somewhere. In this case objects come from classes. A class is a template/blueprint for creating objects. A class has 2 things; characteristics and behaviours.  Characteristics/properties/attributes/data members describe what an object will look like. For example class Book has properties such as title, year, number of pages, and type of cover. These properties give us an idea of what our object is and what it looks like. From just inspecting the properties. One can already determine what kind of class we are talking about. Let us try this, if we have properties like name, surname, age, gender, race, height and ID number; which class do you think this is? Well you are right, it is you; a person.  Behaviours/actions/methods describe the action(s) a particular class can perform. These are normally in the form of verbs. For example, a person can walk, talk, sleep, read, run and eat. Again by looking at these behaviours of an object, it is possible to make out which object we are talking about. Before we can have objects, we need to have a class that will help guide what our objects will look like. You can imagine a class as a capsule, yes that tablet that you take sometimes when you are not feeling okay, it might look something like this: A capsule looks like this picture shown above. Classes help protect and hide sensitive data and processing information from the outside world; this is an OOP feature called encapsulation or information hiding. There is an example I like to use when dealing with classes and objects for the 1st time, and it involves a “cookie cutter” and some cookies. I think all of us love some biscuits, they definitely taste great and they often come out in nice shapes. A cookies cutter is used to cut out the shape of all these biscuits/cookies. A cookie cutter can look like this. Now when baking, dough will be prepared and a cookie cutter shown above will be used to cut out star shaped cookies, and from that one cookie cutter, we can make 100s of cookies of the exact same shape. Here are some cookies below: What we can take from this is the following: The “cookie cutter” represents a class. This provides a blueprint of what the objects are going to look like. And as you can see above, we only have one cookie cutter, and as mentioned already, from this one cutter, we can get many cookies. Same is true of a class. From one class, we can derive or create many more identical objects. Earlier we mentioned that a class looks like a capsule. Let us go back to this for a moment. The data and information of a class is protected in the capsule, and it is organized as shown below: Data Methods Classes consist of data members/attributes/characteristics and methods/behaviours/actions. And these are organized as shown above in the capsule. The data inside the class is normally hidden from the outside world. And the methods are the public interface through which the outside world can communicate with the class and data. The data and methods inside a class have access specifiers. These are levels of access given to the outside world or anyone who is planning on using the class. In C++ we have 3 access specifiers but for now we only focus on two, namely public and private.  Private – access is restricted to any entity outside the class. Normally the data inside your class uses the private access specifier. This is because data is considered sensitive and must be kept hidden from the outside world.  Public – open access normally given to methods inside a class. Methods are normally public, and they are used to control the amount of access or type of access the outside world can have on your class data. When creating a class in C++, there is a specific template that is followed. And below is the basic structure of a class in C++: class ClassName { private: //data members here public: //methods here }; //methods are implemented at this point Looking at the basic structure of a class provided here. Let us take a look at a couple of things. Firstly each class starts with the keyword class. Notice that this keyword starts with a lowercase character, as most C++ keywords do. This is then followed by the name of the class; it is common practice that this name must start with an uppercase character. This name must follow all the variable naming conventions. Immediately after that we have an opening curly brace ({); this is where the body of the class begins and the body of the class ends with a combination of a closing curly brace and semicolon (};). Inside the body of the class is where we are going to declare our members (both data and methods). And as you can see above, class data members are normally designated as private. And methods are mostly (not necessarily always) public. Data members are created simply by stating the data type and name of the member you want to declare. At this point in your class, you are not allowed to give your values any initial values, as this will be done later when implementing methods. The method section of your class consist of declarations of methods, this is very similar to “function prototypes”. Here you are only required to specify a method’s return type, method name and a list of parameters, if there is any. A method and function are totally the same, but the only difference is that a method is a member of a class; so you can simply say that a method is a function that is part of a class. Methods have different categories and purpose as explained below:  Constructors – These are a special type of method that is responsible for giving newly created objects their default values. These methods have the same name as the class, and have not obviously declared return type. These methods are called first, the moment an object is declared. There are two types of constructors, namely default and default overloaded constructors. Default constructors give an object its initial values and do not require any parameters/arguments. Default overloaded constructors also give an object its initial values, but these values are provided in the form of parameters/arguments.  Destructors – These methods also have the same name as the class but their name is preceded by a tilt (~). Unlike constructors, these methods are called when an object goes out of scope.  Setters – These methods are important in providing user provided values to objects. This is done using parameters/arguments. Through setters, the programmer can put measures in place to ensure that they are receiving the type of values they are looking for (validation).  Getters – The name of these methods might be confusing because, their job is actually to return values and not get them. Through these methods, values produced by the class after processing can be sent back to the outside world. Now that we have discussed the finer details of what a class looks like. Now we can go back and try to get some solid examples of what classes can be. Classes represent a general category of things, for instance you can have a class called Book, Product, Vehicle, Customer, Student, Person etc. If you look at these examples of classes you will realise that they are very generic. For instance, if look at class person; we can come up with characteristics/attributes of a person, these are things that each and every one who is a person will have. These may include things like name, surname, age, gender, marital status and race. For each of the listed attributes, each person can provide values that will be unique to that particular person. Meaning that there is one class (blueprint) that requires all this information and each person who will provide this information will be providing information for a person object. There is one person class but from that one class there can be 100s and even 1000s of person object created out of the same class. We will create our first Person class, it will contain some of the data members mentioned above and it will also include some basic methods to help obtain or process person data. Let us have an example of a Person class: #include #include #include using namespace std; class Person { private: string name; int age; char gender; public: Person(); //default constructor void setPerson(string,int,char); //setter string getName(); //getter, returns the string name int getAge(); //getter char getGender(); //getter }; //methods are implemented at this point Above here is what we call the “class definition section”, this is the portion of the class that defines all the data members and methods that will be part of the class. Once all of these have been stated, they are followed up by a class implementation section. Looking at our class we have declared three private data members and five methods, a default constructor, a setter and three getters. Below is the 2nd half of the class, called the “class implementation section”. The implementation section is where you get to specify what each method will perform, by defining each method. Remember that methods are still just the functions, only difference is that these ones belong to a class. So if you have implemented a function before, you will be able to implement a function. Look at the implementation section of the Person class below: //methods are implemented at this point Person::Person() { name = ""; age = 0; gender = ' '; } void Person::setPerson(string nm, int ag, char gn) { name = nm; age = ag; gender = gn; } string Person::getName() { return name; } int Person::getAge() { return age; } char Person::getGender() { return gender; } Above is the class implementation section. There are couple of things we can note from there, let us look at the default constructor first: Person::Person() { name = ""; age = 0; gender = ' '; } First thing to note is that there is not obvious return type as mentioned ealier and secondly we have Person:: ; this is the name of our class followed by a scope resolution operator, the name of a class and this operator are used to link a method to a class you are working on. And in this case the name of the method is Person(), remember this is because we said constructors and destructors have the same name as your class. And the method is simply giving our data members initial values. After the default constructor we have a set method as shown below: void Person::setPerson(string nm, int ag, char gn) { name = nm; age = ag; gender = gn; } As we can see, this method will not return anything (mostly set methods do not return anything) and as such we have void as the return type, followed by the class name and scope resolution operator. We then have the name of the method setPerson, along which a parameterlist is, you must also note that the sequence of our parameter list matches the same order stated in our class definition section for our set method. The main task of the set method is to receive values and assign them to our data members and this is done with the help of our parameterlist. We can also talk about our get methods, as you can see from the code in the class implementation section. Getters or get methods return values and the type of value a particular method is returning must be the method’s return type, see below: int Person::getAge() { return age; } The return type of the method is int because the value the method is returning is an int. And as you can see, the statement inside the method is returning an age. At this point, our class is complete and we must test using our main function. See the code added to the main function below: int _tmain(int argc, _TCHAR* argv[]) { Person ps; //creating an object ps.setPerson("Thato",23,'M'); //calling set method cout

Use Quizgecko on...
Browser
Browser