<<

UNIT 5 OBJECTS AND CLASSES Objects and Classes

Structure 5.1 Introduction Objectives 5.2 ++ as Physical Objects 5.2.1 Objects 5.2.2 Classes 5.2.3 A Complete View of a Class 5.2.4 Scope Operator 5.3 Data Hiding and Encapsulation 5.4 Scope of Class and its Members 5.4.1 Scope of Private and Protected Members 5.4.2 Scope of Public Members 5.5 Global Class and Local Class 5.5.1 Global Class 5.5.2 Local Class 5.6 Functions in Class 5.6.1 Inline Functions 5.6.2 Member Functions 5.6.3 Const Member Functions 5.6.4 Friend Functions 5.7 Nested Classes 5.8 Summary 5.9 Answers to SAQs 5.1 INTRODUCTION

This unit describes about objects and classes. The use of objects in C++ defines the way programs are designed and written. Classes are a software construct that can be used to emulate a real world object. Classes encapsulate data and functions. The fundamental idea behind object-oriented language is to combine into a single program entity, both data and the functions operate on that data. Such an entity is called an object. Till now we have studied different issues, functions related to object oriented like C++. This unit will explain declaration of classes in C++, use of data hiding and encapsulation, scope of classes and its members. Further, different functions are also described with the help of examples in this unit. Objectives After studying this unit, you should be able to • visualize C++ as physical objects, • define objects and classes, • define data members and member functions, • understand scope of the data members and member functions, • understand scope operator for the member function within a class, • use the scope within the classes, • define types of member functions within the class, and 5

Object-oriented • use nested class and communication between classes. Programming Using C++ 5.2 C++ AS PHYSICAL OBJECTS

As you know objects are the basic entities in an object-oriented system. They may represent a person, a place, a table, a vehicle, time or any user defined data, any item that the program needs to handle. 5.2.1 Objects Object is defined as an identifiable entity with some characteristic and behaviour. For instance, we can say ‘Orange’ is an object. Its characteristics are : it is spherical shaped, its colour is orange, etc. Its behaviour is: it is juicy and it tastes sweet-sour. While programming using OOP approach, the characteristics of an object are represented by its data and its behaviour is represented by its functions associated. Therefore, in OOP programming object represents an entity that can store data and has its interface through functions. Programming problem is analyzed in terms of objects and the nature of communication between them, so it is necessary for you to understand the nature of communication between objects. 5.2.2 Classes A class is a group of objects that share common properties and relationships as shown in Figure 5.1. This figure shows how these objects communicate with each other. Let us see in Example 5.1 below how we can declare a class.

Object

Data

Member Function

Member Function

Obj ect Object

Data Data

Member Function Member Function

Member Function Member Function

Figure 5.1 : Communication between Objects Example 5.1 A typical class declaration would look like Class item { int number; float cost; public: void getdata(int a, float b); 6

void putdata(void); } Objects and Classes For instance, a software model of a car, a car “class”, might contain data about the type of car and abilities such as accelerate or decelerate. A class is a programmer defined that has data, its members, and abilities, its methods. An object is a particular instance of a class. This is best understood by an analogy with a built- in data type such as int (integer). int x; /* declares x to be a variable of type int.*/ car impala; /* declares impala to be an object of class car.*/ 5.2.3 A Complete View of a Class A class is a logical method to organize data and functions in the same structure. They are declared using keyword class, whose functionality is similar to that of the C keyword struct, but with the possibility of including functions with a variety of scope (which will be discussed later in this unit) as members, instead of only data. Now let us have a view of a complete class : class class_name { permission_label_1: member1; permission_label_2: member2; ... } object_name; where class_name is a name for the class (user defined type) and the optional field object_name is one, or several, valid object . The body of the declaration can contain members, that can be either data or function declarations, and optionally permission labels, that can be any of these three keywords : private, public or protected. They make reference to the permission which the following members acquire : • private members of a class are accessible only from other members of their same class or from their “friend ” classes. • protected members are accessible from members of their same class and friend classes, and also from members of their derived classes. • public members are accessible from anywhere the class is visible. If we declare members of a class before including any permission , the members are considered private, since it is the default permission that the members of a class declared with the class keyword acquire. For example : class crectangle { int x, y; public: void set_values (int,int); int area (void); } rect; Declares class crectangle and an object called rect of this class (type). This class contains four members: two variables of type int (x and y) in the private section (because private is the default permission) and two functions in the public section: set_values ( ) and area ( ), of which we have only included the prototype.

7

Object-oriented In the previous example, where crectangle was the class name (i.., the user-defined Programming Using C++ type), and rect was an object of type crectangle. Now consider the following declaration of a variable : int a; What is the difference between object declaration and variable declaration? When you analyse you will find that int is the class name (type) and a is the object name (variable). On successive instructions in the body of the program we can refer to any of the public members of the object rect as if they were normal functions or variables, just by putting the object’ name followed by a point and then the class member. For example : rect.set_value (3,4); myarea = rect.area( ); but we will not be able to refer to x or y since they are private members of the class and they could only be referred from other members of that same class . Example 5.2 # include class crectangle { int x, y; public: void set_values(int, int); int area (void) {return(x*y);} }; void crectangle:: set_values (int a, int b) { x = a ; y = b ; } int main ( ) { crectangle rect; rect.set_values (3, 4 ); cout << “area: “ << rect.area ( ) ; } Output : rect area : 12 5.2.4 Scope Operator If you have noticed in the previous example we have used the operator : : of scope in the definition of set_values ( ). Notice that we have defined the behaviour of function area ( ) within the definition of the crectangle class – given its extreme simplicity. Whereas set_values( ) has only its prototype declared within the class but its definition is outside. So in this outside declaration we must use the operator of scope “::”. The scope operator (::) specifies the class to which the member being declared belongs, granting exactly the same scope properties as if it was directly defined within the class. The reason why we have made x and y private members (remember that if nothing else is said all members of a class defined with keyword class have private access) it is because we have already defined a function to introduce those values in the object (set_values( )) and therefore the rest of the program does not have a way to directly access them. 8

One of the greater advantages of a class is that we can declare several different objects Objects and Classes from it. For example, following with the previous example of class crectangle, we could have declared the object rectb in addition to the object rect. Example 5.3 # include class crectangle { int x, y ; public : void set_values (int, int) ; int area (void) {return (x * y) ; } }; void crectangle :: set_values (int a, int b) { x = a; y = b ; } int main ( ) { crectangle rect, rectb; rect.set_values (3,4); rectb.set_values (5,6); cout << "rect area: " << rect.area( ) << endl; cout << "rectb area: " << rectb.area( ) << endl; } Output : rect area: 12 rectb area: 30 Notice that the call to rect.area ( ) does not give the same result as the call to rectb.area ( ). This is because each object of class crectangle has its own variables x and y, and its own functions set_value ( ) and area ( ). On that is based the concept of object and object-oriented programming. In that data and functions are properties of the object, instead of the usual view of objects as function parameters in structured programming. In this and the following sections we will discuss advantages of this methodology. In this concrete case, the class crectangle, of which there are two objects : rect and rectb, each one with its own member variables and member functions. 5.3 DATA HIDING AND ENCAPSULATION

Encapsulation refers to wrapping up data and associated functions into one single unit. The data hiding (using private declaration) is the key feature of object-oriented programming. The class groups its members (data and functions) into three sections : private, protected and public, where private and protected members remain hidden from outside world. Only the member functions can have access to the private data members and private functions. However, the public members (both functions and data) can be accessed from outside the class. This is illustrated in Figure 5.2.

Error! CLASS

9 Private Area No Entry to Private Area

Object-oriented Programming Using C++

Figure 5.2 : Data Hiding in Classes SAQ 1 (a) Explain the difference between a public member and a private member of a class. (b) Explain the difference between the interface and the implementation of a class. (c) Explain the difference between the constructor and destructor. (d) What name must a constructor have?

5.4 SCOPE OF CLASS AND ITS MEMBERS

The scope of a class member depends upon its access-specifier (private, public, protected). In the following section we have explained the scope of public, private and protected members in the class. 5.4.1 Scope of Private and Protected Members The private and protected members of a class can be accessed only by the member function of the class. These members cannot be accessed directly by using the object names. In other words, the names of the private and protected members of the class cannot appear except in the body of the class, let us see an example to understand this. Example 5.4 # include 10

class x Objects and Classes { private : int a; void fc (void) { cout << a; // private data member (a) used by a member function } public : int i; void fcc1 (void) { cout < 2*i; a=13; // private data member (a) used by a member function } }; x Ob1; int main ( ), { Ob1.i= 10; Ob1.fcc1( ); Ob1.a = 5; // invalid. a is private data member Ob1.fc( ); //invalid fc( ) is a private member function ...... ….... } 5.4.2 Scope of Public Members The scope of public members depends upon the object being used for referencing them. If the referencing object is a global object, then the object of public members is also global and if the referencing object is a local object, then the scope of public members is local. Example 5.5 #include class x { private: int a ; void fc(void) { cout << a; } public : 11

Object-oriented int i ; Programming Using C++ void fcc1( void) { cout << 2*i; a = 13; fc( ); } }; x Ob1; // global object Ob1 int main( ) { x Ob2; // local (to main( )) object Ob2 Ob1.i = 10; // Ob1 is global & available to main Ob1.fcc1( ); Ob2.i = 20; // Ob2 is local object available to main( ) Ob2.fcc( ); } void func1( ) { x Ob3; Ob1.i = 12; // Ob1 is global and hence also available to func1( ) Ob1.fcc1( ); // valid Ob2.i = 25; // invalid Ob2 is not available to func1( ) Ob2.fcc1( ) ; // invalid Ob3.i = 15; // valid. Ob3 is locally available to func1( ) Ob3.fcc1( ); // valid ...... } In the above example, Ob1 is a global object, and so the public members of Ob1 can be accessed from any of the functions in the program. Ob2 is a local object, local to function main ( ), and thus, the public members of Ob2 can be accessed only in main ( ) and not in func1 ( ) and not anywhere else. 5.5 GLOBAL CLASS AND LOCAL CLASS

5.5.1 Global Class As you know classes are abstract data types. Similar to other data types, classes can also be classified into global and local category depending upon the factor where we are defining the class. In this section we will discuss about the global-local class and their scope. A class is said to be a global class if its definition occurs outside the bodies of all functions in a program, which means that the object of this class type can be declared from anywhere in the program. Example 5.6

12 # include

class x // global class type x Objects and Classes { ...... }; x Ob_1; //global object of type x int main ( ) { x Ob_2; // local object O2 of type x } void func1(void) { x Ob_3; // local object O3 of type x ...... } In the above program x is a class, defined globally. Thus, an object of type x can be declared from anywhere in the program. The objects Ob_1,Ob_2 and Ob_3 of class type x have been declared at different places in the program. 5.5.2 Local Class A class is said to be a local class if its definition occurs inside a function body, which means that objects of this class type can be declared only within the function that defines this class type. Example 5.7 # include ...... int main( ) { class y // local class type y { ...... }; y Ob_1; // local object Ob1 of type y ...... } void func1(void) { y Ob2; // invalid. Y type is not available in func1( ) ...... // it is available in main( ) that has defined it } SAQ 2 (a) What name must a destructor have? (b) How many constructors can a class have? (c) How many destructors can a class have? (d) How and why is the scope resolution operator :: used in class definitions? 13

Object-oriented Programming Using C++ 5.6 FUNCTIONS IN CLASS

Member functions in classes are a key way to organize C++ programs. One of the important advantages of using functions is that they help us save memory space. As all the calls to the function cause the same code to be executed; the function body need not be duplicated in memory. In 1, Unit 4 we have defined some of these functions. However, in this section we will explain some other issue of these functions with the help of programming examples. 5.6.1 Inline Functions Imagine a situation where a small function is getting called several times in a program. But there are certain overheads involved while calling a function. Time has to be spent on passing values, passing control, returning value and returning control. In such situations to save the execution time you may instruct the C++ compiler to put the code in the function body directly inside the code in the calling program, i.e. at each place where there is a function call in the program, the actual code from the function would be inserted, instead of a jump to the function. Such functions are called inline functions. The only difference between defining a class member function completely within its class and to include only the prototype, is that in the first case the function will automatically be considered inline by the compiler, while in the second it will be a normal (not-inline) class member function. Any function as made inline function by using the keyword inline in the function definition. Let us see given code : inline void func1( ) { // statements } If you need to use a function declaration, it must the inline as well. inline void func1( ); // declaration It is appropriate to inline a function when it is short, but not otherwise. If a long or complex function is inlined, too much memory is used and not much time is saved. Member functions defined within the class specification are inline by default. Ordinary non-member functions are not inline unless inlining is explicitly specified with the inline keyword. To define a member function that is too large to make inline, the function is declared within the class but defined outside it. Let us see an example to understand this. Example 5.8 class anyclass { public: void anyfunc( ); // declaration only }; void anyclass :: anyfunc( ) // definition outside the class { // statements //this function is not inline } Member functions defined outside the class are ordinary – not inline – by default, however, outside defined functions can be made inline by using the inline keyword.

14

Even if a member function is declared within a class specification (or using the keyword Objects and Classes inline explicitly), the compiler may not allow it to be an inline function. The compiler may treat as ordinary functions, issuing warning messages when it does so. 5.6.2 Static Member Functions A static member function is defined using the keyword static. It has the following properties : • A static function can have access to only other static members (functions or variables) declared in the same class. • A static member function can be called using the class name (instead of its objects) as class-name :: function-name; In the following example, we will see how the static member function are used. Example 5.9 class sample { private: static int count; public: sample( ) { count++ ; } static void showcount( ) { cout << endl << “count=” << count; } }; int sample :: count = 0 ; void main( ) { sample s1; sample::showcount( ) ; sample s2 ; sample ::showcount ) ; sample s3 ; sample::showcount( ); } 5.6.3 Const Member Functions A const member function guarantees that it will never modify any of its class’s member data. To understand how the const member functions are used see the example given below. Example 5.10 class sample 15

Object-oriented { Programming Using C++ private: int data; public: sample( ) { data=0; } void changedata( ) { data = 10 ; } void modifydata( ) const { data = 20; //error } void showdata( ) { Cout << endl << “data=” << data ; } }; void main( ) { sample s1; s1.showdata( ) ; s1.changedata( ) ; s1.showdata( ) ; s1.changedata( ) ; s1.showdata( ); } In this example the non-const function changedata ( ) can modify data, but the constant function modifydata ( ) can’t. If it tries to, a compiler error ‘cannot modify a const object’ results. Note that to make modifydata ( ) constant the keyword const is placed after the declator but before the function body. If the function is declared inside the class but defined outside it then it is necessary to use const in declaration as well as definition. Member functions that do nothing but acquire data from an object are obvious candidates for being made const. In our program one such function was showdata ( ), which too could have been made a constant function.

16

5.6.4 Friend Functions Objects and Classes A friend function is a function that is not a member of a class, but nevertheless has access to private and protected members of the class. The policies of encapsulation and data hiding dictate that non-member functions should not be able to access the private data of a class. However, there are situations where such rigid discrimination leads to considerable inconvenience. There could be a situation where we would like to have two classes to share a particular function. For example, consider a case where two classes one and two, have been defined. We would like to use a function accessboth ( ) to have access to private data members of both these classes, hence C++ provides us a friend function. Suppose we want a function to operate on objects of two different classes. If the two classes are inherited from the same base class, then we may be able to put the function in the base class. But if the classes are unrelated then friend function can be used as a bridge between two classes. To understand it further see the example given below. Example 5.11 #include class two; class one { private: int data1; public: one( ) { data1 = 100; } friend int accessboth( one, two); }; class two { private: int data2; public: two( ) { data2 = 200 ; } friend int accessboth(one, two); }; int accessboth( one a, two b) { return( a.data1 + b.data2 ); }

void main( ) 17

Object-oriented { Programming Using C++ one a ; two b ; cout << accessboth (a, b); } To make an outside function “friendly” to a class, we have to declare this function as a friend of the class as shown below: class ABC { ……. ……. public: ……….. …………. friend void xyz(void); //declaration }; The function declaration should be preceded by the keyword friend. The function is defined elsewhere in the program like a normal C++ function. The function definition does not use either the keyword friend or the scope operator ::. The functions that are declared with the keyword friend are known as friend functions. A function can be declared as a friend in any number of classes. A friend function, although not a member function, has full access rights to the private members of the class. A friend function is not in the scope of the class to which it has been declared as friend. Since it is not in the scope of the class, it cannot be called using the object of that class. It can be invoked like a normal function without the help of any object. Unlike member functions, it cannot access the member names directly and has to use an object name and dot membership operator with each member name. It can be declared either in the public or the private part of a class without affecting its meaning. Usually, it has the objects as arguments. Example 5.12 # include class sample { int a ; int b ; public : void setvalue( ) { a = 25; b = 40; } friend float mean (sample s); //friend declared }; float mean (sample s) { return float (s.a + s.b) / 2.0 ; 18

} Objects and Classes main ( ) { sample X ; // object X x.setvalue ( ) ; cout << “Mean value = “ << mean (x) << “\n” ; } Note that the friend function accesses the class variables a and b by using the dot operator and the object passed to it. The function call mean (X) passes the object X by value to the friend function. Member functions of one class can be friend functions of another class. In such cases, they are defined using the scope resolution operator as shown below: class X { ……….. ………. int fun1( ); //member function of X ………. }; class Y { ……. ……. friend int x :: fun1( ) ; // fun1( ) of X // is friend of Y …….. }; The function fun1( ) is a member of class X and a friend of class Y. 5.7 NESTED CLASSES

A nested class can be declared within the scope of another class. Such a class is called a “nested class”. Nested classes are considered to be within the scope of the enclosing class and are available for use within that scope. You can place one class specification inside another as given below in the code. class alpha { private: class beta; { }; 19

Object-oriented }; Programming Using C++ Here, beta is said to be nested inside alpha. If beta is used only by alpha and will never be accessed or instantiated outside alpha, then it makes sense to place it completely within alpha. Another advantage to nested classes is that normal class names and member names have global scope; that is, they are visible throughout the entire program. But in this example, because beta is hidden inside alpha, beta’s member names can be used for other purposes elsewhere without fear of conflict. Such name clashes can be a problem in large programs with thousands of names. It is always a good practice to minimize the number of names in the global name space. 5.7.1 Communication between Nested Classes They do not have automatic access to each other’s data just because they are nested with ordinary non-nested classes, special efforts must be made to allow communication. One approach is to use friend classes. Example 5.13 //one class nested inside another class alpha { private: int adata; class beta { private: int bdata; friend class alpha; public: void bfunc( { alpha obja; obja.adata = 3; } }; // end class beta friend class alpha : : beta ; // beta is a friend of alpha // (must follow beta) public: void afunc( ) { beta objB; objB.bdata = 2 ; objB.bfunc( ); }; // end class alpha

20 void main( )

{ Objects and Classes alpha objA; objA.afunc( ); } The member function afunc ( ) in alpha can access the private bdata in beta, and bfunc ( ) in beta can access the private adata in alpha. friend class alpha :: beta; must follow the specification for beta within alpha specification. It must also use the complete name of beta, which, because it is nested within alpha, is alpha :: beta. Within beta, alpha is made a friend in the usual way. SAQ 3 (a) What is a Null object? (b) Explain the difference between a template class and class template. (c) Explain the difference between a class and a struct. (d) What is global class and local class?

5.8 SUMMARY

In this unit, we have explained different issues of object oriented programming. Encapsulation refers to wrapping up data and functions into one single entity which we have explained in this, data hiding is another concept of object oriented programming which was discussed, further the scope of different members of the class are explained. Different useful functions like inline, static, const and friend available in C++ are explained in this unit with their use in programming. This unit ends up with the explanation of nested class and their scope. The next unit of the block will cover the virtual functions and inheritance. 5.9 ANSWERS TO SAQs

SAQ 1 (a) A public member is accessible from outside the class; a private member is not. (b) The class interface consists of the member data and the member function prototypes (i.e. just the function declarations). The class implementation contains the definitions of the member functions. (c) A constructor is a class member function that executes automatically whenever an object of that class is initiated (i.e. constructed). A destructor is a class member function that executes automatically whenever the scope of the object terminates (i.e. destructed). (d) Every class constructor must have same name as the class itself. SAQ 2 21

Object-oriented (a) Every class destructor must have same name as the class itself, prefixed with Programming Using C++ a tilde (~). (b) There is no limit to the number of constructors that a class may have. But since multiple constructors are function overloads, they must be distinguishable by their parameter lists. (c) A class can have only one destructor. (d) The scope resolution operator :: is used in general “to resolve external references”. It is used in a class definition of a member function is given outside the scope of the class definition. SAQ 3 (a) It is an object of some class whose purpose is to indicate that a real object of that class does not exist. One common use for a null object is a return value from a member function that is supposed to return an object with some specified properties but cannot find such an object. (b) Template class : A generic definition or a parameterized class not instantiated until the client provides the needed information. It’s jargon for plain templates. Class template : A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It’s jargon for plain classes. (c) A class and a struct in C++ are essentially the same. The only siginificant difference is that the default access level for a class is private, while that for struct is public. (d) A class is said to be a global class if its definition occurs outside the bodies of all functions in a program, which means that object of this class type can be declared from anywhere in the program. A class is said to be local class if its definition occurs inside a function body, which means that objects of this class type can be declared only within the function that defines this class type.

22