C++ Session11

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View C++ Session11 as PDF for free.

More details

  • Words: 3,049
  • Pages: 15
Session 11 Introduction to Object Oriented Programming (OOP) & Classes Contents Objectives Introduction 11.1 What is Object Oriented Programming? 11.2 Brief history on Object Oriented Programming 11.3 Classes and Objects 11.3.1 How to declare a class 11.3.2 The relationship between classes and objects 11.3.3 Accessing class members using an object 11.3.4 Access specifiers 11.3.5 A demonstration of accessing public members of a class 11.4 Private member data and accessor methods 11.4.1 A demonstration of the use of ‘private member data’ and ‘accessor methods’ Summary

Objectives After reading this lesson you should be able to:  Understand what objects and classes are  Define a class and create objects of that class  Understand what member functions and member data are  Understand what are access modifiers and the correct use of them  Define accessor methods.

1

Introduction Before the object oriented concepts emerged, a program was viewed as a logical process that is organized around actions. For example, it might take a date as an input, processes it, and produces output data. The programmes we have learnt so far followed this logical process. In the recent decades with the increasing requirements of different processes, programmes became more complex. Hence it became difficult and time consuming in order to create, manage and maintain programmes using the above procedure. In addition, the quality of programmes became more vital and also the new technologies like Graphical User Interfaces (GUI), Internet, digital and wireless technologies emerged. As a result a need of a more organized procedures were required. In order to solve above problems a new concept called ‘Object Oriented Programming’ emerged. This session introduces Object oriented programming concepts which are the most powerful programming concepts that are used in software application and programme development today. This session covers the most important OOP fundamental concepts called classes, objects and methods and also the concept called ‘access modifiers’ and ‘accessor methods’.

11.1 What is Object Oriented Programming? Object-oriented programming (OOP) is a programming technique that uses the concept of ‘objects’ and their interactions between them in order to design computer programs. In OOP a programme needs to be seen as a collection of objects. The interactions between these objects were carried out by sending and receiving messages between objects. In addition these objects are capable of processing data. Each object can be viewed as an independent entity and these objects have their own discrete tasks to perform. messages

Object -a-

Object -b-

messages messages Object -c-

Figure 01 – How objects interact by passing messages 2

11. 2 A brief history of Object Oriented Programming Object-oriented programming concepts first emerged in 1960’s when a group of Software Engineers were working on ship simulations. They wanted to find out how the different characteristics of different ships could affect one another. Finally they decided to group the different types of ships into different classes of objects where each class of object has its own data and behavior. Hence, these concepts of objects were first introduced in the programming language called ‘Simula 67,’ by Ole-Johan Dahl and Kristen Nygaard who were working in the Norwegian Computing Center. These concepts were then used in analog programming which was carried out using analog computers. In 1970’s the term Object-oriented programming were introduced in the language called ‘smalltalk’ in order to represent the concepts of objects and messages. Therefore Smalltalk was the first programming language to be called ‘object-oriented’. This concept was not much popular until mid 1990’s with the popularity of graphical user interfaces, event-driven programming and with the development of computer games. After that, a number of object oriented languages have emerged including C++, Java, as well as Visual Basic .NET and C# which were designed for Microsoft's .NET platform.

11.3 Classes and Objects In order to work with objects it is essential to create classes. A Class is a collection of different types of variables which can hold data and a set of related functions. Classes define the characteristics of objects and the object’s behavior. The variables in a class are referred as member variables or data members. The functions of a class are referred to as member functions or methods of a class. The functions of the class manipulate the member variables of that class.

11.3.1 How to declare a class A class must be declared before it is used. The general format of declaring a class is: class class_name { member1: member2: : : };

3

The word ‘class’ is a keyword used in C++. In declaring a class the keyword needs to be declared followed by the name of the class. Here a suitable class name needs to be specified just like in creating variables. The members and the functions of that class needs to be specified inside curly braces. Any number of members can be included inside a class and the class declaration ends with a semicolon. Example 11.1: Assume that a class called Parrot needs to be declared which has characteristics and behaviors of a parrot. class Parrot{ unsigned int p_age; float p_weight; void Fly(); };

Data members of the class Parrot Methods of the class Parrot

In the above example a class called ‘Parrot’ has been created. The parrot can have several characteristics and some of them are the parrot’s age and its weight. These characteristics have been declared as data members in the class. These data members are declared exactly the manner that normal variable have been declared, which is the type of the data followed by a suitable variable name. A parrot can have different behaviors. Behaviors mean the things that the parrot can do. These behaviors can be declared as methods of the class. One of the behaviors of the parrot is that it can fly. Hence the method called Fly() has been declared. The type of the method has been declared as ‘void’ because the method will not return a value. Any type of methods and any number of methods can be declared inside a class depending on the requirements. Note: In declaring data members and methods it is vital to understand the difference between them. Characteristics are declared as data members and the behaviors are declared as methods of the class.

11.3.2 The relationship between classes and objects Declaring the class doesn’t allocate memory for that class. It is just a way of representing what data that the class has (ex. p_age, p_weight) and what the class can do. (ex. Fly()) A class needs to be accessed through objects. An object can also be defined as a particular instance of a class. Consider the example given in 11.1. In the example the class Parrot do not represent a single parrot, rather it represent all possible parrots by listing the characteristics and behaviors they all can have. In creating objects a specific parrot/object needs to be declared which has a specific age and a weight.

4

There is a general format for declaring an object from a class. That is the class name followed by the object name followed by a semicolon. class_name object_name; Example 11.2: Parrot Nicky; Object name can be any name, which is suitable for the identification of that object. Here an object named Nicky has been created assuming that a name of a parrot is Nicky. This object called ‘Nicky’ is an instance of the class Parrot. Note: A class can have any number of objects.

11.3.3 Accessing class members using an object Using the object that was created it is possible to access the class data members and methods. The general format for accessing the members of a class is: Object_name.member_name; According to example 11.2 since a new object has been created an age and a weight needs to be assigned to the newly created object. Example 11.3: Nicky.p_age=2; //Assigning 2 to age Nicky.p_weight=1.5; //Assigning 1.5 to weight Nicky.Fly(); // Accessing the Fly method. Note: Values being assigned to the data members of an object and NOT to a class. Parrot.p_age=2; // This is an error

11.3.4 Access specifiers There is a special concept that is used in accessing the members of a class. The concept is based on what are called ‘access specifiers’ and there are three types of access specifiers used in C++. These are denoted using three C++ keywords called, ‘private’, ‘public’, ‘protected’ and are used to define the access rights of a class.  Private: All the data and methods in a class are private by default. The private members of a class are accessible from within the methods of the same class. In addition ‘friend’ functions can also access the private members of a class. (Friend functions will be covered in the sessions to come.)

5

 Public: Public members can be accessed by any object of the class.  Protected: This accessed specifier is similar to the private accessed specifier. Protected members are accessible from within the methods of the same class and from their friends, but also from members of their derived classes. (Derived classes will be covered under Inheritance in the sessions to come) Consider example 11.1. The access specifier is not declared in the class declaration. Hence all the members are private by default. As a result these data and methods cannot be accessed inside the main method because the private members of a class are accessible only from within the methods of the same class. The main method is not a method of the class Parrot. For this reason these members need to be declared as public in order to access it. Example 11.4: class Parrot{ public: unsigned int p_age; float p_weight; void Fly(); }; These concepts will be explained clearly using the example given below.

11.3.5 A demonstration of accessing public members of a class 1. #include 2. #include 3. class Parrot{ 4. public: 5. unsigned int p_age; 6. float p_weight; 7. 8. 9. 10. };

void Fly(){ cout<<"Flying....!"; }

11. void main() 12. { 13. clrscr();

6

14. Parrot Nicky; 15. Nicky.p_age=2; 16. Nicky.p_weight=1.5; 17. cout<<"Nicky's age is "<
Nicky's age is 2 Nicky's weight is 1.5 Flying....!

In the example given above, a class called ‘Parrot’ has been declared. The body of the class is from line 3 to line10. The class has two public data members called p_age, p_weight and one public method called Fly(). Inside the main method an object called Nicky has been declared in line 14 as an instance of the class Parrot. Values set to the object’s p_age and p_weight. (Line 15 and 16). Then the data members are used again to print messages and the method Fly() is called in line 19. The methods need not to be defined inside the class itself. It is possible to define the methods outside the class declaration using the operator of scope (::, two colons). The prototype of the method needs to be included inside the class if the method is defined outside the scope of the class. (ex. void Fly();) Example11.5: class Parrot{ public: unsigned int p_age; float p_weight; void Fly(); }; void Parrot::Fly(){ cout<<"Flying....!"; } In declaring methods outside of the class, the type of the method followed by the class name (Ex. void Parrot) needed to be included in order to declare that the method is a member of that class and not just a global function.

7

Activity 11.1 – Creating a class and accessing its public members Declare a class called ‘Car’ and two public data members, which can store the number of seats in the car and the engine capacity. Declare two public methods called ‘Move’ and ‘Stop’ which don’t return any value and print two different messages inside the methods. Create two instances of the class. Set values to the data members of the instances. Call the ‘Move’ method for one object and call the ‘Stop’ method for the other object.

11.4 Private member data and accessor methods Members that are declared before an access specifier automatically have private access. Example 11.6: class Parrot{ unsigned int p_age; float p_weight; public: void Fly(){ cout<<"Flying....!"; } }; In the example 11.6, p_age and the p_weight are private members whereas the method is a public method. Normally as a general rule, data members in a class are declared as private members. As mentioned before, when the data members are declared as private, it is not possible to access them inside the main method. Therefore it is essential to have public methods to access these private member variables. These are called ‘accessor methods’. The accessor methods are defined as the member functions/methods of the class and is used to read the value of a class (get methods) as well as to set a value in a member variable (set methods). Hence these accessor methods provide a public interface in order to access the private members of the class.

8

11.4.1 A demonstration of the use of ‘private member data’ and ‘accessor methods’ 1. #include 2. #include 3. class Parrot{ 4. public: 5. //Declaring accessor functions for p_age 6. unsigned int getAge(); 7. void setAge(unsigned int age); 8. 9. 10.

//Declaring accessor function for p_weight float getWeight(); void setWeight(float weight);

11.

void Fly(); //General function

12. private: 13. unsigned int p_age; 14. float p_weight; 15. }; 16. //Defining accssor methods 17. unsigned int Parrot::getAge(){ 18. return p_age; 19. } 20. void Parrot::setAge(unsigned int age){ 21. p_age=age; 22. } 23. float Parrot::getWeight(){ 24. return p_weight; 25. } 26. void Parrot::setWeight(float weight){ 27. p_weight=weight; 28. } 29. //Defining general methods 30. void Parrot::Fly(){ 31. cout<<"Flying....!\n"; 32. } 9

33. void main() 34. { 35. clrscr(); 36. Parrot Nicky; //Creating an instance 37. Nicky.setAge(2); 38. Nicky.setWeight(1.5); 39. cout<<"Nicky's age is "<
Nicky's age is 2 Nicky's weight is 1.5 Flying....!

In the above programme, line 3 to line 15 contains the class definition. There are five public methods and two private data members. The members declared after the keyword public are a set of public members and the members declared after the keyword private are a set of private members. In order to access the data member p_age, the two methods called setAge() and getAge has been declared (Refer line 6 & 7) and to access the data member p_weight, the two methods called setWeight() and getWeight() has been declared (Refer line 9 & 10). The void Fly() is declared in line 11 which is a general method that prints a massage on the screen. From line 16 to 28, all the accessor methods have been defined. The functions are declared using the operator of scope (::), which indicates that the methods are a member function of the class Parrot. The first accessor method getAge() is of type unsigned int. It doesn’t take any parameters into the function but it returns the value p_age. Since the main method cannot access p_age directly as it is a private data member, using the method getAge() the p_age can be accessed (Refer line 39) and the massage ‘Nicky's age is 2’ is printed. The setAge() method takes ‘age’ as an arguments to the function since the main method can’t access p_age directly. When the age of the parrot is set inside the main method as 2 (Refer line 37), the value is passed to the method setAge() function and the value ‘age’ is assigned to p_age which means the value 2 is assigned to p_age. Hence it is evident that the setAge() and getAge() methods acts as an public interface in order to access the private member p_age.

10

The methods setWeight() and getWeight() also behave in a similar manner to the methods setAge() and getAge().

Activity 11.2 – The use of private member data and accessor methods

Rewrite the programme in activity 11.1 using private member data and accessor methods.

Summary  Object-oriented programming (OOP) is a programming technique that uses the concept of ‘objects’ and their interactions between them.  A Class is a collection of different types of variables, which can hold data and a set of related functions. The variables in a class are referred as member variables or data members. The functions of a class are referred to as member functions or methods of a class.  Object is a particular instance of a class and classes are accessed using objects.  Classes define the characteristics of objects, and the object’s behavior. These characteristics have been declared as data members in the class. These behaviors can be declared as methods of the class.  There are three types of accessed specifiers called, ‘private’, ‘public’ and ‘protected’.  All the data and methods in a class are private by default  Accessor methods can be used to access the private member data of a class.

11

Session 11 – Answers Activity 11.1 - Answer #include #include class Car{ public: unsigned int seats; float engine_capacity; void Move(){ cout<<"It is moving....!"; } void Stop(){ cout<<"It has stopped....!"; } }; void main() { clrscr(); Car mycar; mycar.seats=2; mycar.engine_capacity=1300; cout<<"My car has "<<mycar.seats<<" seats"<<endl; cout<<"Engine capacity is "<<mycar.engine_capacity<<"cc"<<endl; mycar.Move(); cout<<"\n\n"; Car yourcar; yourcar.seats=5; yourcar.engine_capacity=1500; cout<<"Your car has "<
Output:

My car has 2 seats Engine capacity is 1300cc It is moving....! Your car has 5 seats Engine capacity is 1500cc It has stopped!

Activity 11.2 – Answer #include #include class Car{ public: //Declaring accessor functions for getSeats unsigned int getSeats(); void setSeats(unsigned int s); //Declaring accessor function for getCapacity float getCapacity(); void setCapacity(float capacity); //General functions void Move(); void Stop(); private: unsigned int seats; float engine_capacity; }; //Defining accssor methods unsigned int Car::getSeats(){ return seats; } void Car::setSeats(unsigned int s){ seats=s; }

13

float Car::getCapacity(){ return engine_capacity; } void Car::setCapacity(float capacity){ engine_capacity=capacity; } //Defining general methods void Car::Move(){ cout<<"It is moving....!\n"; } void Car::Stop(){ cout<<"It has stopped....!\n"; } void main() { clrscr(); Car mycar; //Creating an instance mycar.setSeats(2); mycar.setCapacity(1300); cout<<"My car has "<<mycar.getSeats()<<" seats"<<endl; cout<<"Engine capacity is "<<mycar.getCapacity()<<"cc"<<endl; mycar.Move(); cout<<"\n\n"; Car yourcar; //Creating an instance yourcar.setSeats(5); yourcar.setCapacity(1500); cout<<"Your car has "<
14

Output: My car has 2 seats Engine capacity is 1300cc It is moving....! Your car has 5 seats Engine capacity is 1500cc It has stopped!

15

Related Documents

C++ Session11
November 2019 1
Session11 Solution
November 2019 7
08 Asp.net Session11
June 2020 2
C-c++
November 2019 73
C C
December 2019 93