Chapter 8

Classes and Objects

CHAPTER OUTLINE
8.1  INTRODUCTION

In C, structures are used to define custom or user-defined data type. Structure is a combination of same or different data types. Only variables are declared inside a structure. The initialization of member variables inside the structure is not permitted. Objects can directly access the data members of the structures.

Fig. 8.1 Structures in C

Functions are not permitted as members in structure. Outside functions are also able to access the data members of the structure through the object. Thus, there is no security to data members declared inside the structure in C as shown in Figure 8.1.

In C++, structure also combines function with data members. C++ introduces new keyword class. A class in C++ is similar to structure. Using class or structure, a programmer can merge one or more dissimilar data types and a new custom data type can be created. A class is nothing but grouping of variables of different data types with functions. Each variable of a class is called as member variable. Functions are called as member functions or methods.

In C++, it is possible to access data members directly by objects, which is not possible in C. It is always the programmer’s choice to allow or disallow the direct access of data members. The mechanism of restricting access of data outside the class is called as data hiding or encapsulation. In such a case, only the member functions can access the data. If class is used in place of struct, it restricts the access of data members as shown in Figure 8.2.

Fig. 8.2 class in C++

8.2  STRUCTURE IN C

In C, it is possible to combine dissimilar data types using structure but it has the following limitations:

  • Functions are not allowed as members of structure.
  • Direct access to data members is possible. So, by default all the structure members are public. Hence, security to data or data hiding is not provided.
  • The struct data type is not treated as built-in type; that is the use of struct keyword is necessary to declare objects.
  • The data members cannot be initialized inside the structure.

The syntax of structure declaration is as follows:

 

syntax:

struct <struct name>

{

Variable1;

Variable2;

};

Example:

sruct item

{

int codeno;

float prize;

int qty;

};

In the above example, item is a structure name. The data members are codeno, prize, and qty. Thus, a custom data type is created by combination of one or more data members.

The object of structure item can be declared as follows:

 

struct item a,*b

The object declaration is same as the declaration of variables of built-in data types. The object a and the pointer *b are variables of type item and each of them has three data members. The a and *b can access the data members of struct item. Use of keyword struct is necessary.

Access to structure members: The data members of a structure are accessed by using object name and operators such as dot (.) or arrow (->). The dot (.) or arrow (->) operators are known as referencing operators. The dot operator is used when simple object is declared and arrow operator is used when object is pointer to structure. The access of members can be accomplished as given in the following syntax:

[Object name][Operator][Member variable name]

When an object is a simple variable, access of members is done as follows:

Object name dot(.) member variable name

 

a.codeno

a.price

a.qty

When an object is a pointer to structure then members are accessed as follows:

a->codeno

a->price

a->qty

Note: A structure declaration must have a name or identifier followed by keyword struct, else the compiler will display an error. This is because it will not recognize the type of object declared. Hence, there is no possibility of accessing the structure member variables.

The following program illustrates the above discussion.

 

8.1 Write a program to access data members of a structure.

#include<stdio.h>

#include<conio.h>

struct item // struct declaration

{

int codeno; // codeno=200 not possible as per 8.2 section

float prize;

int qty;

};

void main()

{

struct item a,*b; // object declaration

clrscr();

a.codeno=123; // direct access & initialization of member variables

a.prize=150.75;

a.qty= 150;

printf (“ With simple variable”);

printf (“ Codeno : %d ”,a.codeno);

printf (“ Prize : %d”,a.prize);

printf (“ Qty : %d”,a.qty);

b->codeno=124; // direct access & initialization of member variables

b->prize=200.75;

b->qty= 75;

printf (“ With pointer variable”);

printf (“ Codeno : %d ”,b->codeno);

printf (“ Prize : %d”,b->prize);

printf (“ Qty : %d”,b->qty);

}

 

OUTPUT

With simple variable

Codeno : 123

Prize : 150.75

Qty : 150

With pointer to structure

Codeno : 124

Prize : 200.75

Qty : 75

Explanation: The above program is compiled with C compiler. The following discussion is according to C compiler. In the above program, the structure item is declared with three member variables. The initialization of member variables inside the struct is not permitted. The declaration of member variables is enclosed within the curly braces. The struct declaration is terminated with a semicolon.

In function main(), the objects a and b are declared. Consider the following statement.

 

struct item a,*b; // object declaration

The struct must be preceded by structure name. The member variables can be accessed and initialization is done directly by object. The dot and arrow operators are used to access the member variables.

8.3  STRUCTURE IN C++

No doubt, C++ has made various improvements in structure. To know the improvements made in C++, the last program is compiled and executed with C++ compiler. The explanation followed by this program discusses the various improvements.

 

8.2 Write a program to declare struct. Initialize and display contents of data members.

#include<iostream.h>

#include<conio.h>

struct item // struct declaration

{

int codeno; // codeno=200 not possible

float prize;

int qty;

};

int main()

{

item a,*b; // object declaration

clrscr();

a.codeno=123; // direct access & initialization of member variables

a.prize=150.75;

a.qty= 150;

cout<<“ With simple variable”;

cout<<“ Codeno : ”<<a.codeno;

cout<<“ Prize : ”<<a.prize;

cout<<“ Qty : ”<<a.qty;

b->codeno=124; // direct access & initialization of member variables

b->prize=200.75;

b->qty= 75;

cout<<“ With pointer to structure”;

cout<<“ Codeno : ”<<b->codeno;

cout<<“ Prize : ”<<b->prize;

cout<<“ Qty : ”<<b->qty;

return 0;

}

Explanation: The above program is the same as previous one. The output is also same, hence not shown. Consider the following statement.

 

item a,*b; // object declaration in c++

 

While declaring an object, the keyword struct is omitted, which is compulsory in C. The structure item is a user-defined data type. C++ itself behaves as a structure data type which is built-in type and allows variable declaration.

C++ introduces new keyword class, which is similar to structure. The other improvements are discussed with the use of class in the following section.

8.4  CLASSES IN C++

A class is used to pack data members and member function together. The class has a mechanism to prevent direct access to its members, which is the central idea of object-oriented programming. The whole declaration of class is given in Table 8.1. The class declaration is also known as formation of new abstract data type. The abstract data type can be used as basic data type such as int, float, etc.

 

Table 8.1 Syntax and an Example of class

Syntax of class Declaration

Example of class

class <name of class>

{

private:

declaration of variables;

prototype declaration of function;

public:

declaration of variables;

prototype declaration of function;

};

class item // class declaration

{

private:

int codeno;

float prize;

int qty;

void values();

public:

void show();

};

The class is a keyword. The class declaration is same as struct declaration. The declaration of a class is enclosed with curly braces and terminated with a semicolon. The data members and member functions can be declared in two sections, that is private and public. The private and public keywords are terminated with a colon (:). The object cannot directly access the data members and member functions declared in private section, but it can access the data member and member functions declared in public section. The private members of a class can only be accessed by a public member function of the same class. Different sections of class are illustrated with examples in the following sections.

It is also possible to access private member variables directly like public member variables provided that the class should have at least one public member variable. Both the private and public member variables are stored in consecutive memory locations in the memory. A pointer to member variable provides address of member variable. By applying increment (++) and decrement (--) operations on pointer, we can access all private and public member variables of the class. The object of a class contains address of the first member variable. It can be also used to access the private or public data.

8.5  DECLARING OBJECTS

A class declaration only builds the structure of an object. The member variables and functions are combined in the class. The declaration of objects is same as declaration of variables of basic data types. Defining objects of class data type is known as class instantiation. Only when objects are created, memory is allocated to them.

Consider the following examples.

 

  • int x,y,z; // Declaration of integer variables
  • char a,b,c; // Declaration of character variables
  • item a,b, *c; // Declaration of object or class type variables

In the example (a), three variables x, y, and z of int types are declared. In the example (b), three variables a, b, and c of char type are declared. In the same fashion the third example declares the three objects a, b, and c of class item. The object *c is pointer to class item.

An object is an abstract unit with the following properties:

  • It is individual.
  • It points to a thing, either physical or logical that is identifiable by the user.
  • It holds data as well as operation method that handle data.
  • Its scope is limited to the block in which it is defined.

Access to class members: The object can access the public data member and member functions of a class by using dot (.) and arrow (->) operators. The syntax is as follows:

[Object name][Operator][Member name]

To access data members of class the statement would be as follows:

 

a.show();

where a is an object and show() is a member function. The dot operator is used because a is a simple object.

In statement

 

c->show();

*c is pointer to class item; therefore, the arrow operator is used to access the member.

Consider the given example.

 

class item // class declaration

{

int codeno;

float prize;

int qty;

};

We replaced the struct keyword with class. If programs 8.1 and 8.2 are executed with class, they will not work. For example,

 

void main()

{

item a,*b; // object declaration

clrscr();

a.codeno=123; // Direct access is not allowed

a.prize=150.75;

a.qty= 150;

}

The above program will generate error messages such as “‘item::codeno is not accessible. This is because the object cannot directly access the member variables of a class, which is possible with structure. Hence, we can say that the difference between class and struct is that the member variables of struct can be accessed directly by the object, whereas the member variables of class cannot be accessed directly by the object.

8.6  THE public KEYWORD

In Section 8.3, we noticed that the object directly accesses the member variables of structure, whereas the same is not possible with class members. The keyword public can be used to allow objects to access the member variables of a class directly like structure. The public keyword is written inside the class. It is terminated with a colon (:). The member variables and functions declared followed by the keyword public can be accessed directly by the object. The declaration can be done as follows:

 

class item // class declaration

{

public: // public section begins

int codeno;

float prize;

int qty;

};

Consider the following program that illustrates the use of public keyword with class.

 

8.3 Write a program to declare all members of a class as public. Access the elements using object.

#include<iostream.h>

#include<conio.h>

class item

{

public: // public section begins

int codeno;

float prize;

int qty;

}; // end of class

int main()

{

clrscr();

item one; // object declaration

one.codeno=123; // member initialization

one.prize=123.45;

one.qty=150;

cout<<“ Codeno = ”<<one.codeno;

cout<<“ Prize = ”<< one.prize;

cout<<“ Quantity = ”<<one.qty

return 0;

}

OUTPUT

Codeno = 123

Prize =123.449997

Quantity =150

Explanation: In the above program, the members of class item are declared followed by keyword public. The object one of class item accesses the member variables directly. The member variables are initialized and values are displayed on the screen.

8.7  THE private KEYWORD

The private keyword is used to prevent direct access of member variables or function by the object. The class by default produces this effect.

The structure variables by default are public. To prevent member variables and functions of struct from direct access, the private keyword is used. The syntax of private keyword is same as public. The private keyword is terminated with a colon. Consider the following example.

 

struct item

{

private: // private section begins

int codeno;

float prize;

int qty;

}; // end of class

int main()

{

clrscr();

item one; // object declaration

one.codeno=123; // member initialization

one.price=123.45;

one.qty=150;

}

As soon as the above program is compiled, the compiler will display the following error message:

‘item::codeno’ is not accessible

‘item::prize’ is not accessible

‘item::qty’ is not accessible

‘item::codeno’ is not accessible

‘item::prize’ is not accessible

From the above discussion, we noticed that by default (without applying public or private keyword) the class members are private (not accessible) whereas the struct members are public (accessible).

The private members are not accessible by the object directly. Then the question is how will they be accessed? To access the private members of a class, member functions of the same class are used. The member function must be declared in the class in public section. A program on accessing private members is given in the forthcoming sections. Through the public member function, an object can access the private members.

8.8  THE protected KEYWORD

The access mechanism of protected keyword is same as private keyword. We cannot access protected section members from outside the class by any object.

The following example clears the above concept:

 

8.4 Write a program using class to declare member variable and function under protected section and make an attempt to access them using object.      

#include<iostream.h>

#include<conio.h>

class A

{

protected:

int num;

void display()

{

cout<<num;

}

};

int main()

{

A a;

a.num=100;

a.display();

return 0;

}

Note: The above program gives an error A::num and A::display() are not accessible.

The protected keyword is frequently used in inheritance of classes. Its detailed description is given Chapter 11.

8.9  ACCESS SPECIFIERS AND THEIR SCOPE

As described in Table 8.2, the class object can access a public member of the class directly without the use of member function. The private and protected mechanisms do not allow an object to access data directly. The object can access private or protected members only through public member functions of the same class.

 

Table 8.2 Access Limits of class Members

Access Specifiers
Access Permission
class Members
class Members

Public

Allowed

Allowed

Private

Allowed

Disallowed

Protected

Allowed

Disallowed

The following program explains the working of the above keywords:

 

8.5 Write a program using class to declare member variable and functions private, public and protected section and make an attempt to access them using object.

#include<iostream.h>

#include<conio.h>

class sample

{

private:

int num;

void show1()

{

cout<<“Inside the private section”;

cout<<“ Enter a number:”;

cin>>num;

cout<<“Number is:”<<num;

}

public:

int num1;

void show()

{

show1();

cout<<“ Inside the public section”;

cout<<“ Enter a number:”;

cin>>num1;

cout<<“Number is:”<<num1;

show2();

}

protected:

int num2;

void show2()

{

cout<<“ Inside the protected section”;

cout<<“ Enter a number:”;

cin>>num2;

cout<<“Number is:”<<num2;

}

};

int main()

{

sample s;

s.show();

return 0;

}

OUTPUT

Inside the private section

Enter a number:4

Number is:4

Inside the public section

Enter a number:5

Number is:5

Inside the protected section

Enter a number:6

Number is:6

8.10  DEFINING MEMBER FUNCTIONS

The member function must be declared inside the class. They can be defined as (a) private or public section and (b) inside or outside the class. The member functions defined inside the class are treated as inline function. If the member function is small then it should be defined inside the class. Otherwise, it should be defined outside the class.

If function is defined outside the class, its prototype declaration must be done inside the class. While defining the function, scope access operator and class name should precede the function name. The following programs illustrate all about member function and how to access the private member of the class.

8.10.1  Member Function Inside the class

Member function inside the class can be declared in public or private section. The following program illustrates the use of a member function inside the class in public section.

 

8.6 Write a program to access private members of a class using member function.

#include<iostream.h>

#include<conio.h>

class item

{

private: // private section starts

int codeno;

float price;

int qty;

public: // public section starts

void show() // member function

{

codeno=125; // access to private members

price=195;

qty=200;

cout<<“ Codeno =”<<codeno;

cout<<“ Price =”<<price;

cout<<“ Quantity=”<<qty;

}

};

int main()

{

clrscr();

item one; // object declaration

one.show(); // call to member function

return 0;

}

OUTPUT

Codeno =125

Price =195

Quantity=200

Explanation: In the above program, the member function show() is defined inside the class in public section. In function main(), object one is declared. We know that an object has a permission to access the public members of the class. The object one invokes the public member function show(). The public member function can access the private members of the same class. The function show() initializes the private member variables and displays the contents on the console. For the sake of understanding only one function is defined.

In the above program the member function is defined inside the class in public section. Now the following program explains how to define private member function inside the class.

8.10.2  Private Member Function

In the last section, we learned how to access private data of a class using public member function. It is also possible to declare a function in private section like data variables. To execute private member function, it must be invoked by public member function of the same class. A member function of a class can invoke any other member function of its own class. This method of invoking function is known as nesting of member function. When one member function invokes other member function, the frequent method of calling function is not used. The member function can be invoked by its name terminated with a semicolon only like normal function. The following program illustrates this point.

 

8.7 Write a program to declare private member function and access it using public member function.

#include<iostream.h>

#include<conio.h>

struct item

{

private: // private section starts

int codeno;

float price;

int qty;

void values() // private member function

{

codeno=125;

price=195;

qty=200;

}

public: // public section starts

void show() // public member function

{

values(); // call to private member functions

cout<<“ Codeno =”<<codeno;

cout<<“ Price =”<<price;

cout<<“ Quantity=”<<qty;

}

};

int main()

{

clrscr();

item one; // object declaration

// one.values(); // not accessible

one.show(); // call to public member function

return 0;

}

OUTPUT

Codeno =125

Price =195

Quantity=200

Explanation: In the above program, the private section of a class item contains one-member function values(). The function show() is defined in public section. In function main(), one is an object of class item. The object one cannot access the private member function. In order to execute the private member function, the private function must be invoked using public member function. In this example, the public member function show() invokes the private member function values(). In the invocation of function values(), object name and operator are not used.

8.10.3   Member Function Outside the class

In the previous examples, we observed that the member functions are defined inside the class. The function prototype is also not declared. The functions defined inside the class are considered as inline functions. If a function is small, it should be defined inside the class and if large it must be defined outside the class. To define a function outside the class, following care must be taken.

  • The prototype of function must be declared inside the class.
  • The function name must be preceded by class name and its return type separated by scope access operator.

The following example illustrates the function defined outside the class.

 

8.8 Write a program to define member function of class outside the class.

#include<iostream.h>

#include<conio.h>

class item

{

private: // private section starts

int codeno; // member data variables

float price;

int qty;

public: // public section starts

void show (void); // prototype declaration

}; // end of class

void item:: show() // definition outside the class

{

codeno=101;

price=2342;

qty=122;

cout<<“ Codeno =”<<codeno;

cout<<“ Price =”<<price;

cout<<“ Quantity=”<<qty;

}

int main()

{

clrscr();

item one; // object declaration

one.show(); // call to public member function

return 0;

}

OUTPUT

Codeno =101

Price =2342

Quantity=122

Explanation: In the above program, the prototype of function show() is declared inside the class terminated by class definition. The body of function show() is defined inside the class. The class name that it belongs to and its return type precede the function name. The function declarator of function show() is as follows:

 

void item:: show()

 

where void is return type; that is function is not returning a value. The item is a class name. Scope access operator separates the class name and function name, followed by the body of function that is defined.

8.11  CHARACTERISTICS OF MEMBER FUNCTIONS
  1. The difference between member and normal function is that the formal function can be invoked freely, whereas the latter function only by using an object of the same class.
  2. The same function can be used in any number of classes. This is possible because the scope of the function is limited to their classes and cannot overlap one another.
  3. The private data or private function can be accessed by public member function. Other functions have no access permission.
  4. The member function can invoke one another without using any object or dot operator.
8.12  OUTSIDE MEMBER FUNCTION AS INLINE

In Chapter 7, we learned how inline mechanism is useful for small function. It is good practice to declare function prototype inside the class and definition outside the class. The inline mechanism reduces overhead relating to access the member function. It provides better efficiency and allows quick execution of functions. An inline member function is similar to macros. Call to inline function in the program, puts the function code in the caller program. This is known as inline expansion. Inline functions are also called as open subroutines because their code is replaced at the place of function call in the caller function. The normal functions are known as closed subroutines because when such functions are called, the control passes to the function.

By default, all member functions defined inside the class are inline function. The member function defined outside the class can be made inline by prefixing the keyword inline to function declarator as shown in Figure 8.3.

Fig. 8.3 Inline function outside the class

The inline is a keyword and acts as function qualifier. The return type is functions return type; that is the function returns values of this type. The class name is the name of class that the function belongs to. Scope access operator separates class name and function name. The signature means argument list passed function. The following program illustrates inline function outside the class.

 

8.9 Write a program to make an outside function as inline.

#include<iostream.h>

#include<conio.h>

class item

{

private: // private section starts

int codeno; // member data variables

float price;

int qty;

public: // public section starts

void show (void); // prototype declaration

}; // end of class

inline void item:: show() // outside inline function

{

codeno=213;

price=2022;

qty=150;

cout<<“ Codeno =”<<codeno;

cout<<“ Price =”<<price;

cout<<“ Quantity=”<<qty;

}

int main()

{

clrscr();

item one; // object declaration

one.show(); // call to public member function (inline)

return 0;

}

OUTPUT

Codeno =213

Price =2022

Quantity=150

Explanation: The above program is same as last one. The only difference is that the function show() is defined as inline outside the class. The function declarator is as follows inline void item::show().

8.13  RULES FOR INLINE FUNCTIONS
  1. Inline function should be used rarely. It should be applied only at appropriate circumstances.
  2. Inline function can be used when the member function contains few statements. For example,

     

    inline int item :: square (int x)

    {

    return (x*x);

    }

     

  3. If function takes more time to execute, then it must be declared as inline. The following inline function cannot be expanded as inline.

     

    inline void item:: show()

    {

    cout<<“ Codeno =”<<codeno;

    cout<<“ Price =”<<price;

    cout<<“ Quantity=”<<qty;

    }

The member function that performs input and output operation requires more times. Inline functions have one drawback, the entire code of the function is placed at the point of call in caller function and it must be noted at compile time. Therefore, inline functions cannot be placed in standard library or run time library.

8.14  DATA HIDING OR ENCAPSULATION

Data hiding is also known as encapsulation. It is a procedure of forming objects. An encapsulated object is often called as an abstract data type. We need to encapsulate data, because programmer often makes various mistakes and the data get changed accidentally. Thus, to protect data, we need to construct a secure and impassable wall to protect the data. Data hiding is nothing but making data variable of the class or struct private. Thus, private data cannot be accessed directly by the object. The objects using public member functions of the same class can access the private data of the class. The keywords private and protected are used for hiding the data. Table 8.2 shows the brief description of access specifiers. The following program explains data hiding:

 

8.10 Write a program to calculate simple interest. Hide the data elements of the class using private keyword.      

#include<iostream.h>

#include<conio.h>

class interest

{

private :

float p_amount; // principle amount

float rate; // rate of interest

float period; // numbers of years

float interest;

float t_amount; // total amount

public :

void in()

{

cout<<“ Principle Amount : ”; cin>>p_amount;

cout<<“ Rate of Interest : ”; cin>>rate;

cout<<“ Number of years : ”; cin>>period;

interest=(p_amount*period*rate)/100;

t_amount=interest+p_amount;

}

void show()

{

cout<<“ Principle Amount : ”<<p_amount;

cout<<“ Rate of Interest : ”<<rate;

cout<<“ Number of years : ”<<period;

cout<<“ Interest : ”<<interest;

cout<<“ Total Amount : ”<<t_amount;

}

};

int main()

{

clrscr();

interest r;

r.in();

r.show();

return 0;

}

OUTPUT

Principle Amount : 5000

Rate of Interest : 2

Number of years : 3

Principle Amount : 5000

Rate of Interest : 2

Number of years : 3

Interest : 300

Total Amount : 5300

Explanation: In the above program, the class interest is declared with the data members p_amount, float rate, period, 4, and t_amount of float type. These entire data elements are declared in private section; hence, it is hidden (encapsulated) and cannot be directly accessed by the object. Here, member functions in() is used to read data through the keyboard. The function show() is used to display the contents of the variables.

 

8.11 Write a program to declare class with private, public and private sections. Declare object and access data elements of these different sections.

#include<iostream.h>

#include<conio.h>

class access

{

private :

int p;

void getp()

{

cout<<“ In pget() enter value of p :”;

cin>>p;

}

public:

int h;

void geth()

{

cout<<“ In geth() : ”<<end1;

getp();

getm();

cout<<“ p = ”<<p <<“ h = ”<<h <<“ m = ”<<m;

}

protected :

int m;

void getm()

{

cout<<“ In mget() enter value of m : ”;

cin>>m;

}

};

int main()

{

clrscr();

access a; // object declaration

// a.p=2; // access to private member is not possible.

// a.pget() // -----------” ----------------

// a.m=5; // access to protectd member is not possible

// a.mget(); // ----------------” ---------------------

a.h=4; // direct access to public member is possible

a.geth();

return 0;

}

OUTPUT

In geth():

In pget() enter value of p:7

In mget() enter value of m: 4

p = 7 h = 4 m = 4

Explanation: In the above program, the class access is declared with private, protected, and public sections. Each section holds one integer variable and one member function. The object cannot directly access the data variable and member function of the private and protected sections. The object can access only the public section of the class and through public section it can access the private or protected section. Here, the object an accesses the public variable h and initializes it with 4 whereas the private and protected variables are accessed using member functions. The function getp() and getm() are invoked by the public member function geth(). The geth() also displays the contents of the variables on the screen.

8.15  CLASSES, OBJECTS, AND MEMORY

Objects are the identifiers declared for class data type. Object is a composition of one more variables declared inside the class. Each object has its own copy of public and private data members. An object can access to its own copy of data members and have no access to data members of other objects.

Only declaration of a class does not allocate memory to the class data members. When an object is declared, memory is reserved for only data member and not for member functions.

Consider the following program.

 

8.12 Write a program to declare objects and display their contents.

#include<iostream.h>

#include<constream.h>

class month

{

public:

char *name;

int days;

}; // end of class

int main()

{

clrscr();

month M1,M3; // object declaration

M1.name=”January”;

M1.days=31;

M3.name=”March”;

M3.days=31;

cout<<“ Object M1 ”;

cout<<“ Month name : ”<<M1.name <<“ Address :”<<(unsigned)&M1.name;

cout<<“ Days :” <<M1.days <<“ Address : ”<<(unsigned)&M1.days;

cout<<“ Object M3 ”;

cout<<“ Month name : ”<<M3.name <<“ Address : ”<<(unsigned)&M3.name;

cout<<“ Days :” <<M3.days <<“ Address : ”<<(unsigned)&M3.days;

return 0;

}

OUTPUT

Object M1

Month name : January Address :65522

Days : 31 Address : 65524

Object M3

Month name : March Address : 65518

Days : 31 Address : 65520

Explanation: M1 and M3 are objects of class month. Separate memory is allocated to each object. The contents and address of the member variables are displayed in the output. Figure 8.4 shows it more visibly.

Fig. 8.4 Memory occupied by objects

From the last program it is clear that memory is allocated for data members. What about functions? Member functions are created and memory is allocated to them only once when a class is declared. All objects of a class access the same memory location where member functions are stored. Hence, separate copies of member functions are not present in every object like member variables, which is illustrated in the following program and Figure 8.5.

 

8.13 Write a program to display the size of the objects.

#include<iostream.h>

#include<constream.h>

class data

{

long i; // By default private

float f;

char c;

};

int main()

{

clrscr();

data d1,d2;

cout<<endl<<“ Size of object d1 = ”<<sizeof(d1);

cout<<endl<<“ Size of object d2 = ”<<sizeof(d2);

cout<<endl<<“ Size of class =”<<sizeof(data);

return 0;

}

OUTPUT

Size of object d1 = 9

Size of object d2 = 9

Size of class = 9

Explanation: In the above program, the class data has three member variables of long, float, and char type. The d1 and d2 are objects of the class data. The sizeof operator displays the size of objects. The size of any object is equal to the sum of sizes of all the data members of the class. In the class data, the data type long occupies 4 bytes, float occupies 4 bytes, and char occupies 1 byte. Their sum is 9, which equals the size of an individual object.

The member functions are not considered in the size of the object. All the objects of a class use the same member functions. Only one copy of member function is created and stored in the memory whereas each object has its own set of data members.

Fig. 8.5 Data members and member functions in memory

8.16  static MEMBER VARIABLES

We noticed that each object has a separate set of data member variables in memory. The member functions are created only once and all objects share the functions. No separate copy of function of each object is created in the memory like data member variables.

It is possible to create common member variables like function using the static keyword. Once a data member variable is declared as static, only one copy of that member is created for the whole class. The static is a keyword that is used to preserve the value of a variable. When a variable is declared as static it is initialized to zero. A static function or data element is only recognized inside the scope of the present compile.

In earlier version of Turbo C++, it was not necessary to explicitly define static data members. It was linkers’ responsibility to find undefined static data. The linker would implicitly define the static data and allocate the required memory without showing error message. In new versions of Turbo C++, it is necessary to explicitly define static members.

 

Syntax:

static <variable definition> ;

static <function definition>;

If a local variable is declared with static keyword, it preserves the last value of the variable. A static data item is helpful when all the objects of the class should share a common data. The static data variable is accessible within the class, but its value remains in the memory throughout the whole program (Figure 8.6).

 

Examples:

static int c;

static void display() {}

a) int sumnum :: c=0;

Fig. 8.6 static members in memory

The class and scope of the static member variable is defined outside the class declaration as per the statement (a). The reasons are as follows:

  1. The static data members are associated with the class and not with any object.
  2. The static data members are stored individually rather than an element of an object.
  3. The static data member variable must be initialized otherwise the linker will generate an error.
  4. The memory for static data is allocated only once.
  5. Only one copy of static member variable is created for the whole class for any number of objects. All the objects have common static data member.

8.14 Write a program to declare static data member. Display the value of static data member

#include<iostream.h>

#include<constream.h>

class number

{

static int c;

public:

void count()

{

++c;

cout<<“ c=”<<c;

}

};

int number :: c=0; // initialization of static member variable

int main()

{

number a,b,c;

clrscr();

a.count();

b.count();

c.count();

return 0;

}

OUTPUT

c=1

c=2

c=3

Explanation: In the above program, the class number has one static data variable c. The count() is a member functions’ increment value of static member variable c by one when called. The statement int number::c=0 initializes the static member with 0. It is also possible to initialize the static data members with other values. In the function main() a, b, and c are three objects of class number. Each object calls the function count(). At each call to the function count(), the variable c gets incremented and the cout statement displays the value of the variable c. The objects a, b, and c share the same copy of static data member c.

 

8.15 Write a program to show the difference between static and non-static member variables.

#include<iostream.h>

#include<conio.h>

class number

{

static int c; // static variable

int k; // non-static variable

public:

void zero()

{

k=0;

}

void count()

{

++c;

++k;

cout<<“ Value of c = ”<<c <<“ Address of c = ”<<(unsigned)&c;

cout<<“ Value of k = ”<<k <<“ Address of k = ”<<(unsigned)&k;

}

};

int number :: c=0; // initialization of static member variable

int main()

{

number A,B,C;

clrscr();

A.zero();

B.zero();

C.zero();

A.count();

B.count();

C.count();

return 0;

}

OUTPUT

Value of c = 1 Address of c = 11138

Value of k = 1 Address of k = 85524

Value of c = 2 Address of c = 11138

Value of k = 1 Address of k = 65522

Value of c = 3 Address of c = 11138

Value of k = 1 Address of k = 65520

Explanation: This program compares between static and non-static member variables. The class number has two member variables c and k. The variable c is declared as static and k as normal variable. The function zero() is used to initialize the variable k with zero. The static member variable c is initialized with zero as follows:

 

int number::c=0; // initialization of static member variable

The function count() is used to increment values of c and k. In function main(), A, B, and C are objects of class number. The function zero() is invoked three times by object A, B, and C. Each object has its own copy of variable k, and, hence, each object invokes the function zero() to initialize its copy of k. The static member variable c is common among the object A, B, and C. Hence, it is initialized only once. Figure 8.7 shows the object and member variables in memory.

Fig. 8.7 static and non-static members

8.16 Write a program to enter a number. Count the total number of digits from 0 to 9 occurring from 1 to entered number.      

#include<iostream.h>

#include<conio.h>

class digit

{

static int num[10];

public :

void check(int n);

void show();

void input();

void ini();

};

int digit :: num[]={0,0,0,0,0,0,0,0,0,0};

void digit :: show()

{

for (int j=0;j<10;j++)

{

if (num[j]==0) continue;

cout<<“ Number ”<<j <<“ occurs ” <<num[j] <<“ times”;

}

}

void digit :: ini()

{

for (int k=0;k<10;k++)

num[k]=0;

}

void digit :: input()

{

int x,y;

cout<<endl<<“ Enter a Number : ”;

cin>>y;

check(y);

}

void digit :: check (int u)

{

int m;

while (u!=0)

{

m=u%10;

num[m]++;

u=u/10;

}

}

int main()

{

clrscr();

digit d;

// d.ini();

d.input();

d.show();

return 0;

}

OUTPUT

Enter Numbers Number : 22151

Number 1 occurs 2 times

Number 2 occurs 2 times

Number 5 occurs 1 times

Explanation: In the above program, the class digit is declared with one static array member num[10] and four member functions check(), show(), input(), and ini(). The function input() reads an integer through the keyboard. The entered number is passed to function check(). The function check() is invoked by function input(). The function check() separates individual digits of the entered number using repetitive modular division and division operation. The separated digits are counted and the count value is stored in the array num[10] according to the element number. The function show() displays the contents of array num[]. The function ini() is declared and when called initializes all array elements with zero. In case the array is not declared as static, this function is useful. Here, in this program the array is static, hence we initialized it with the statement int digit::num[]={0,0,0,0,0,0,0,0,0,0}. If this statement is removed, we need to call the function ini().

8.17  static MEMBER FUNCTIONS

Like member variables, function can also be declared as static. When a function is defined as static, it can access only static member variables and functions of the same class. The not-static members are not available to these functions. The static member function declared in public section can be invoked using its class name without using its objects. The static keyword makes the function free from the individual object of the class and its scope is global in the class without creating any side effect for other part of the program. The programmer must follow the following points while declaring static function:

  1. Just one copy of a static member is created in the memory for entire class. All objects of the class share the same copy of static member.
  2. static member function can access only static data members or functions.
  3. static member function can be invoked using class name.
  4. It is also possible to invoke static member functions using objects.
  5. When one of the objects changes the value of data member variables, the effect is visible to all the object of the class.

8.17 Write a program to declare static member functions and call them from the main() function.

#include<iostream.h>

#include<conio.h>

class bita

{

private :

static int c;

public :

static void count() { c++; }

static void display()

{

cout<<“ Value of c : ”<<c;

}

};

int bita ::c=0;

int main()

{

clrscr();

bita:: display();

bita::count();

bita::count();

bita::display();

return 0;

}

OUTPUT

Value of c : 0

Value of c : 2

Explanation: In the above program, the member variables c and functions of class bita are static. The function count() when called increases the value of static variable c. The function display() prints the current value of the variable c. The static function can be called using class name and scope access operator from the following statements:

 

bita::count(); // invokes count() function

bita::display(); // invokes display() function

8.17.1  static Private Member Function

A static member function can also be declared in private section. The private static function must be invoked using static public function. The following program illustrates the point.

 

8.18 Write a program to define private static member function and invoke it.

#include<iostream.h>

#include<conio.h>

class bita

{

private :

static int c;

static void count() { c++; }

public:

static void display()

{

count(); // Call to private static member function

cout<<“ Value of c : ”<<c;

}

};

int bita ::c=0;

int main()

{

clrscr();

bita:: display();

bita::display();

return 0;

}

OUTPUT

Value of c : 1

Value of c : 2

Explanation: In the above program, count() is a private static member function. The public static function display() invokes the private static function count(). The function display() also displays the value of static variable c.

8.17.2  static Public Member Variable

The static public member variable can also be initialized in function main() like other variables. The static member variable using class name and scope access operator can be accessed. The scope access operator is also used when variables of same name are declared in global and local scope, which is illustrated in the following program:

 

8.19 Write a program to declare static public member variable, global and local variable with the same name. Initialize and display their contents.

#include<iostream.h>

#include<constream.h>

int c=11; // global variable

class bita

{

public:

static int c;

};

int bita ::c=22; // class member variable

int main()

{

clrscr();

int c=33; // local variable

cout<<“ Class member c = ”<<bita::c;

cout<<“ Global variable c = ”<<::c;

cout<<“ Local variable c = ”<<c;

return 0;

}

OUTPUT

Class member c = 22

Global variable c = 11

Local variable c = 33

Explanation: In the above program, the variable c is declared and initialized in three different scopes such as global, local, and inside the class. The variable c declared inside is static variable and initialized to 22. The global variable c is initialized to 11 and local variable c is initialized to 33.

static member variable: The value of static variable is displayed using variable name preceded by class name and scope access operator as per the statement cout<<“ Class member c = ”<<bita::c;

Global variable: The global variable can be access using variable name preceded by scope access operator from the statement cout<<“ Global variable c = ”<<::c;.

Local variable: The local variable can be access only by putting its name as per the statement cout<<“ Local variable c = ”<<c;

8.18  static OBJECT

In C, it is common to declare variable static and it gets initialized to zero. The object is a composition of one or more member variables. There is a mechanism called constructor to initialize member variables of the object to desired values. The constructors are explained in the next chapter. The static keyword can be used to initialize all class data member variables to zero. Declaring object itself as static can do this. Thus all its associated members get initialized to zero. The following program illustrates the working of static object.

 

8.20 Write a program to declare static object. Display its contents.

#include<iostream.h>

#include<constream.h>

class bita

{

private:

int c;

int k;

public :

void plus()

{

c+=2;

k+=2;

}

void show()

{

cout<<“ c= ”<<c<<“ ”;

cout<<“ k= ”<<k;

}

};

int main()

{

clrscr();

static bita A;

A.plus();

A.show();

return 0;

}

OUTPUT

c= 2

k= 2

Explanation: The class bita has two member variables c and k and two member functions plus() and show(). In function main(), the object A is declared. It is also declared as static. The data members of object A are initialized to zero. The function plus() is invoked, which adds 2 to the values of c and k. The function displays values of c and k. Declare object static does not mean that entire class is static including member function. The declaration of static object removes garbage of its data members and initializes them to zero.

8.19  ARRAy OF OBJECTS

Arrays are collection of similar data types. Arrays can be of any data type including user-defined data type created using struct, class, and typedef declarations. We can also create an array of objects. The array elements are stored in continuous memory locations as shown in Figure 8.8. Consider the following example.

 

class player

{

private:

char name [20];

int age;

public:

void input (void);

void display (void);

};

The player is a user-defined data type and can be used to declare an array of object of type player. Each object of an array has its own set of data variables.

 

player cricket[5];

player football [5];

player hockey [5];

Fig. 8.8 Arrays of objects

As shown above, arrays of object of type player are created. The array cricket[5] contains name and age information for five objects. The next two declarations can maintain the same information for other player in arrays hockey[5] and football[5]. These arrays can be initialized or accessed like an ordinary array. The following program describes the working of array of objects.

 

8.21 Write a program to declare the array of objects. Initialize and display the contents of arrays.

#include<iostream.h>

#include<constream.h>

class player

{

private:

char name [20];

int age;

public:

void input (void);

void display (void);

};

void player :: input()

{

cout<<“ Enter Palyer name : ”;

cin>>name;

cout<<“ Age : ”;

cin>>age;

}

void player :: display()

{

cout<<“ Player name : ”<<name;

cout<<“ Age : ”<<age;

}

int main()

{

clrscr();

player cricket[3]; // array of objects

cout<<“ Enter Name and age of 3 players ”;

for (int i=0;i<3;i++)

cricket[i].input();

for (i=0;i<3;i++)

cricket[i].display();

return 0;

}

OUTPUT

Enter Name and age of 3 players

Enter Palyer name : Sachin

Age : 29

Enter Palyer name : Rahul

Age : 28

Enter Palyer name : Saurav

Age : 30

Player name : Sachin

Age : 29

Player name : Rahul

Age : 28

Player name : Saurav

Age : 30

Explanation: In the above program, the member function input() reads information of players. The display() function displays information on the screen. In function main() the statement player cricket[3]; creates an array cricket[3] of three objects of type player. The for loops are used to invoke member function input() and display() using array of objects.

8.20  OBJECTS AS FUNCTION ARGUMENTS

Similar to variables, object can be passed to functions. The following are the three methods to pass argument to a function:

  • Pass-by-value – A copy of object (actual object) is sent to function and assigned to the object of callee function (formal object). Both actual and formal copies of objects are stored at different memory locations. Hence, changes made in formal object are not reflected to actual object.
  • Pass-by-reference – Address of object is implicitly sent to function.
  • Pass-by-address – Address of the object is explicitly sent to function.

In pass-by-reference and pass-by-address methods, an address of actual object is passed to the function. The formal argument is reference/pointer to the actual object. Hence, changes made in the object are reflected to actual object. These two methods are useful because an address is passed to the function and duplicating of object is prevented.

The following examples illustrate both the methods of passing objects to the function as an argument.

 

8.22 Write a program to pass objects to the function by pass-by-value method.      

#include<iostream.h>

#include<conio.h>

class life

{

int mfgyr;

int expyr;

int yr;

public :

void getyrs()

{

cout<<“ Manufacture Year : ”;

cin>>>mfgyr;

cout<<“ Expiry Year : ”;

cin>>>expyr;

}

void period ( life);

};

void life :: period (life y1)

{

yr=y1.expyr-y1.mfgyr;

cout<<“Life of the product : ” <<yr <<“ Years”;

}

int main()

{

clrscr();

life a1;

a1.getyrs();

a1.period(a1);

return 0;

}

OUTPUT

Manufacture Year : 1999

Expiry Year : 2002

Life of the product : 3 Years

Explanation: In the above program, the class life is declared with three member integer variables. The function getrys() reads the integers through the keyboard. The function period() calculates the difference between the two integers entered. In the function main(), a1 is an object to the class life. The object a1 calls the function getyrs(). Immediately after this, the same object (a1) is passed to the function period(). The function period() calculates the difference between two integers (dates) using the two data members of the same class. Thus, an object can be passed to the function. To pass an object by reference, the prototype of function period() should be as follows:

 

void period ( life &);

 

8.23 Write a program to pass objects to the function pass-by-address method.

#include<iostream.h>

#include<conio.h>

class life

{

int mfgyr;

int expyr;

int yr;

public :

void getyrs()

{

cout<<“ Manufacture Year : ”;

cin>>>mfgyr;

cout<<“ Expiary Year : ”;

cin>>>expyr;

}

void period ( life*);

};

void life :: period (life *y1)

{

yr=y1->expyr-y1->mfgyr;

cout<<“Life of the product : ” <<yr;

}

int main()

{

clrscr();

life a1;

a1.getyrs();

a1.period(&a1);

return 0;

}

OUTPUT

Manufacture Year : 1999

Expiry Year : 2002

Life of the product : 3 Years

Explanation: The above program is same as previous one. In this program, the object a1 is passed by address. Consider the following statements.

 

  • void period ( life*);
  • a1.period (&a1);
  • Yr=y1->expyr-y1->mfgyr;

The statement (a) is the prototype of the function period(). In this statement, the deference operator (*) indicates that the function will accept address of the actual argument. The statement (b) is used to pass the address of the argument to the function period(). The statement (c) is used to access the member variables of the class. When an object is a pointer to the class members, then its elements are accessed by using arrow (->) operator. In this case, use of a dot operator (.) is invalid.

8.21  friend FUNCTIONS

The central idea of encapsulation and data hiding concept is that any non-member function has no access permission to the private data of the class. The private members of the class are accessed only from member functions of that class.

C++ allows a mechanism, in which a non-member function has access permission to the private members of the class. This can be done by declaring a non-member function friend to the class whose private data is to be accessed. The friend is a keyword. Consider the following example.

 

class ac

{ private:

char name [15];

int acno;

float bal;

public:

void read();

friend void show-bal();

};

The keyword friend must precede the function declaration, whereas function declarator must not. The function can be defined at anyplace in the program like normal function. The function can be declared as friend function in one or more classes. The keyword friend or scope access operator must not precede the definition of the friend function. The declaration of friend function is done inside the class in private or public part and a function can be declared as friend function in any number of classes. These functions use objects as arguments. Thus the following statement is wrong.

 

a) friend void :: showbal (ac a) // Wrong function definition

{

statement1;

statement2;

}

The above declaration of function is wrong because the function declarator precedes the keyword friend.

The friend functions have the following properties:

  • There is no scope restriction for the friend function; hence, they can be called directly without using objects.
  • Unlike member functions of class, the friend cannot access the member directly. On the other hand it uses object and dot operator to access the private and public member variables of the class.
  • By default, friendship is not shared (mutual). For example, if class X is declared as friend of Y, this does not meant that Y has privileges to access private members of class X.
  • Use of friend functions is rare, since it violates the rule of encapsulation and data hiding.
  • The function can be declared in public or private sections without changing its meaning.

8.24 Write a program to access private data using non-member function. Use friend function.

#include<iostream.h>

#include<conio.h>

class ac

{

private:

char name[15];

int acno;

float bal;

public:

void read()

{

cout<<“ Name :” ;

cin>>>name;

cout<<“ A/c No. :”;

cin>>>acno;

cout<<“ Balance :”;

cin>>>bal;

}

friend void showbal(ac ); // friend function declaration

};

void showbal (ac a)

{

cout<<“ Balance of A/c no. ” <<a.acno <<“ is Rs.” <<a.bal;

}

int main()

{

ac k;

k.read();

showbal(k); // call to friend function

return 0;

}

OUTPUT

Name :Manoj

A/c No. :474

Balance :40000

Balance of A/c no. 474 is Rs.40000

Explanation: In the above program, class ac is declared. It has three member variables and one member function. Also, inside the class ac, showbal() is a function, which is declared as friend of the class ac. Once the outside function is declared as friend to any class, it gets an authority to access the private data of that class. The function read() reads the data through the keyboard such as name, account number, and balance. The friend function showbal() display the balance and acno.

 

8.25 Write a program to declare friend function in two classes. Calculate the sum of integers of both the classes using friend sum() function.

#include<iostream.h>

#include<conio.h>

class first;

class second

{

int s;

public :

void getvalue()

{

cout<<“ Enter a number : ”;

cin>>>s;

}

friend void sum (second, first);

};

class first

{

int f;

public :

void getvalue()

{

cout<<“ Enter a number : ” ;

cin>>>f;

}

friend void sum (second, first);

};

void sum (second d, first t)

{

cout<<“ Sum of two numbers : ” <<t.f + d.s;

}

int main()

{

clrscr();

first a;

second b;

a.getvalue();

b.getvalue();

sum(b,a);

}

OUTPUT

Enter a number: 7

Enter a number: 8

Sum of two numbers: 15

Explanation: In the above program, two classes first and second are declared with one integer and one member function in each. The member function getvalue() of both classes reads integers through the keyboard. In both the classes the function sum() is declared as friend. Hence, this function has an access to the members of both the classes. Using sum(), function addition of integers is calculated and displayed.

 

8.26 Write a program to exchange values between two classes. Use friend functions.

#include<iostream.h>

#include<conio.h>

class second;

class first

{

int j;

public:

void input()

{

cout<<“Enter value of j : ”;

cin>>>j;

}

void show (void)

{

cout<<“ Value of J = ”;

cout<<j <<“ ”;

}

friend void change (first &, second &);

};

class second

{

int k;

public :

void input()

{

cout<<“ Enter value of k : ”;

cin>>>k ;

}

void show (void)

{

cout<<“ Value of K = ”;

cout<<k ;

}

friend void change (first &, second &);

};

void change ( first &x, second &y)

{

int tmp=x.j;

x.j=y.k;

y.k=tmp;

}

main()

{

clrscr();

first c1;

second c2;

c1.input();

c2.input();

change (c1,c2);

cout<<“ After change values are” <<“ ”;

c1.show();

c2.show();

return 0;

}

OUTPUT

Enter value of j : 4

Enter value of k : 8

After change values are

Value of J = 8

Value of K = 4

Explanation: In the above program, two classes first and second are defined. Each class contains one integer variable and two member functions. The function input() is used to read an integer through the keyboard. The function show() is used to display the integer on the screen. The function change() is declared as friend function for both the classes. Passing values by reference of member variables of both the classes, values are exchanged.

 

8.27 Write a program to declare three classes. Declare integer array as data member in each class. Perform addition of two data member array into array of third class. Use friend function.

#include<iostream.h>

#include<conio.h>

class B;

class C;

class A

{

int a[5];

public :

void input();

friend C sum (A,B,C);

};

void A :: input()

{

int k;

cout<<“ Enter five integers : ”;

for (k=0;k<5;k++)

cin>>a[k];

}

class B

{

int b[5];

public :

void input();

friend C sum (A,B,C);

};

void B:: input()

{

int k;

cout<<“ Enter five integers : ”;

for (k=0;k<5;k++)

cin>>b[k];

}

class C

{

int c[5];

public :

void show();

friend C sum (A,B,C);

};

void C :: show()

{

cout<<“ Addition : ”;

for (int k=0;k<5;k++)

cout<<“ ” <<c[k];

}

C sum (A a1, B b1, C c1)

{

for (int k=0;k<5;k++)

c1.c[k]=a1.a[k]+b1.b[k];

return c1;

}

int main()

{

clrscr();

A a;

B b;

C c;

a.input();

b.input();

c=sum(a,b,c);

c.show();

}

OUTPUT

Enter five integers : 5 4 8 7 5

Enter five integers : 2 4 1 2 3

Addition : 7 8 9 9 8

Explanation: In the above program, three classes A, B, and C are declared. Each class contains single integer arrays as data member a[5], b[5], and c[5], respectively. The class A and B contains member function input() to read integers. The function sum() is declared as friend in all the three classes. This function performs addition of arrays of class A and B and stores results in the array of class C. The result obtained is returned in main() where the return value is assigned to object c. In main() a, b, and c are objects of classes A, B, and C, respectively. The member function show() of class C displays the contents of object c.

8.21.1   friend Classes

It is possible to declare one or more functions as friend functions or an entire class can also be declared as friend class. When all the functions need to access another class in such a situation we can declare an entire class as friend class. The friend is not transferable or inheritable from one class to another. Declaring class A to be a friend of class B does not meant class B a friend of class A; that is, friendship is not exchangeable. The friend classes are applicable when we want to make available private data of a class to another class.

 

8.28 Write a program to declare friend classes and access the private data.

#include<iostream.h>

#include<constream.h>

class B;

class A

{

private :

int a;

public :

void aset() {a=30;}

void show (B);

};

class B

{

private :

int b;

public :

void bset() { b=40 ;};

friend void A :: show (B bb);

};

void A :: show (B b)

{

cout<<“ a = ”<<a;

cout<<“ b = ”<<b.b;

}

int main()

{

clrscr();

A a1;

a1.aset();

B b1;

b1.bset();

a1.show(b1);

}

OUTPUT

a = 30

b = 40

Explanation: In the above program, two classes A and B are declared. The class A is friend of class B. The member function of class A can access the data of class B. Thus, the show() function displays the values of data members of both the classes.

 

8.29 Write a program to demonstrate friend classes.

#include<iostream.h>

#include<conio.h>

class CPP;

class C

{

private :

int j;

public :

void set() { j=22; }

friend CPP;

};

class CPP

{

public :

void joy(C a)

{

cout<<endl<<“ j = ”<<a.j;

}

void joya(C o)

{

cout<<endl<<“ j = ”<<o.j;

}

};

int main()

{

clrscr();

C x;

CPP y;

x.set();

y.joy(x);

y.joya(x);

return 0;

}

OUTPUT

j = 22

j = 22

Explanation: In the above program, class C and class CPP are declared as friend. The class CPP is declared as friend class of class C. Member function of class CPP can access the private data variables of the class C.

8.22  THE const MEMBER FUNCTIONS

The member functions of a class can also be declared as constant using const keyword. The constant functions cannot modify any data in the class. The const keyword is suffixed to the function prototype as well as in function definition. If these functions attempt to change the data, compiler will generate an error message.

 

8.30 Write a program to declare const member function and attempt any operation within it.

#include<iostream.h>

#include<conio.h>

class A

{

int c;

public :

void add (int a,int b) const

{

// c=a+b; // invalid statement

a+b;

cout<<“a+b = ”<<_AX ;

}

};

int main()

{

clrscr();

A a;

a .add(5,7);

return 0;

}

OUTPUT

a+b = 12

Explanation: In the above program, the class A is declared with one member variable (c) and one constant member function add(). The add() function is invoked with two integers. The constant member function cannot perform any operation. Hence, the expression c=a+b will generate an error. The expression a+b is valid and cannot alter any value. The result obtained from the equation a+b is displayed using CPU register.

8.23  THE VOLATILE MEMBER FUNCTION

In C++, one can declare a member function with volatile specifies. This step leads to call safely the volatile object. Calling volatile member function with volatile object is safe. This concept is supported with the following programming example.

 

8.31 Write a program to call a volatile member function from a volatile object.

#include<iostream.h>

#include<conio.h>

class A

{

private:

int x;

public:

void f() volatile // The volatile member function

{

int x=10;

cout<<“Value of x:”<<++x;

}

};

int main()

{

clrscr();

volatile A c; // The c is a volatile object

c.f(); // Call a volatile member function safely

return 0;

}

OUTPUT

Value of x:11

Explanation: The volatile member function f() is called from a volatile object c and the value of x is initialized to 10. Its value is increased by one and displayed on the screen.

8.24  RECURSIVE MEMBER FUNCTION

Like C, C++ also supports recursive feature; that is, a function is called repetitively by itself. The recursion can be used directly or indirectly. The direct recursion function calls to itself until the condition is true. In indirect recursion, a function calls to another function and then the called function calls to the calling function. Here, the recursion with member function is illustrated in the following program:

 

8.32 Write a program to calculate triangular number by creating a member function. Call it recursively.      

#include<iostream.h>

#include<conio.h>

class num

{

public :

tri_num(int m)

{ int f=0;

if (m==0)

return(f);

else

f=f+m+tri_num(m-1);

return (f);

}

};

int main()

{

clrscr();

num a;

int x;

cout<<“ Enter a number : ”;

cin>>x;

cout<<“Triangular number of ”<<x<<“ is : ”<<a.tri_num(x);

return 0;

}

OUTPUT

Enter a number : 5

Triangular number of 5 is : 15

Explanation: In the above program, class num is declared with one member function tri_

num(). This function is used to calculate the triangular number of the entered number. The triangular number is nothing but the sum from 1 to the number entered. In function main(), a number is read through the keyboard and it is passed to function tri_num(), which is invoked by the object a of class num. The tri_num() is invoked and tri_num() invokes itself repetitively till the value of m becomes 0. The variable f holds the cumulative total of successive numbers and return() statement returns value of f in function main(), where it displays triangular number on the screen.

8.25  LOCAL CLASSES

When classes are declared inside the function then such classes are called as local classes. The local classes have access permission to global variables as well as static variables. The global variables need to be accessed using scope access operator when the class itself contains member variable with same name as global variable. The local classes should not have static data member and static member functions. If at all they are declared, the compiler provides an error message. The following programs illustrate the local classes.

 

8.33 Write a program to define classes inside and outside main() function and access the elements.

#include<iostream.h>

#include<conio.h>

class A

{

private :

int a;

public :

void get()

{

cout<<“ Enter value for a : ”;

cin>>>a;

}

void show()

{ cout<<endl<<“ a = ” <<a; }

};

main()

{

clrscr();

class B

{

int b;

public :

void get()

{

cout<<“ Enter value for b : ”;

cin>>>b;

}

void show()

{

cout<<“ b = ” <<b;

}

};

A j;

B k;

j.get();

k.get();

j.show();

k.show();

return 0;

}

OUTPUT

Enter value for a : 8

Enter value for b : 9

a = 8 b = 9

Explanation: In the above program, class A is declared before main() function as usual. The class B is declared inside the main() function. Both the functions have two member functions get() and show(). The get() function reads integers through the keyboard. The show() functions display the values of data members on the screen.

 

8.34 Write a program to declare global variables, read and display data using member functions.

#include<iostream.h>

#include<conio.h>

int j, k, l, m; // global variable

class A

{

private :

int a;

int j;

public :

void get()

{

cout<<“ Enter value for a,j,j and k : ”;

cin>>>a >>j>>::j >>k;

}

void show()

{

cout<<endl<<“ a = ” <<a <<“ j = ”<<j <<“ ::j = ”<<::j <<“ k = ”<<k ;

}

};

int main()

{

clrscr();

class B

{

int b;

int l;

public :

void get()

{

cout<<“ Enter value for b,l,l and m : ”;

cin>>>b >>l>>::l>>m;

}

void show()

{

cout<<“ b = ” <<b <<“ l = ”<<l <<“ ::l = ”<<::l <<“ m = ”<<m;

}

};

A x;

B y;

x.get();

y.get();

x.show();

y.show();

return 0;

}

OUTPUT

Enter value for a,j,j and k : 1 2 3 4

Enter value for b,l,l and m : 5 6 4 3

a = 1 j = 2 ::j = 3 k = 4

b = 5 l = 6 ::l = 4 m = 3

Explanation: The above program is so far same as previous one. In addition, in this program global variables j, k, l, and m are declared. The member functions get() and show() read and display values of member variables as well as global variables. Here, both the classes contain a single data member variable with the same name as global variables. Thus, to access the global variable where necessary, scope access operator is used. The output of the program is as shown in the above program.

8.26  empty, static, and const CLASSES

The classes without any data members or member functions are called as empty classes. These types of classes are not frequently used. The empty classes are useful in exception handling. For exception handling, refer the chapter 19 exception handling. The syntax of empty class is as follows:

 

EMPTY CLASSES

class nodata { };

class vacant { };

We can also precede the declaration of classes by the keywords static, const, volatile, etc. But there is no any effect in the class operations. Such declaration can be done as follows:

 

CLASSES AND OTHER KEYWORDS

static class boys { };

const class data { };

volatile class area { };

8.27  MEMBER FUNCTION AND NON-MEMBER FUNCTION

So far we used non-member function main() for declaring objects and calling member functions. Apart from main() function other non-member functions can also be used. The member function can also invoke a non-member function and vice versa. When a member function calls a non-member function, it is necessary to put its prototype inside the calling function or at the beginning of the program. It is a better practice to put prototype at the beginning of the program that is visual to the entire program. It is also possible to put definition of the non-member function before class declaration. This method allows member function to invoke outside non-member function without need of prototype declaration. But this approach creates problem when an outside non-member function attempts to invoke member function.

We know that member functions can be called using object of that class. If a non-member function is defined before class declaration, it is not possible to create an object in that function. Hence, the best choice is to put prototype of the non-member function at the beginning of the program that makes easy for both non-member function and member function to call each other. The following program explains practically whatever we learned about member function and non-member function in this section.

 

8.35 Write a program to call a member function using non-member function.

#include<iostream.h>

#include<conio.h>

void moon(void); // Function prototype declaration

class mem

{

public :

void earth() { cout<<“On earth”; }

};

int main()

{

clrscr();

mem k;

moon();

return 0;

}

void moon()

{

mem j;

j. earth();

cout<<endl<<“On moon ”;

}

OUTPUT

On earth

On moon

Explanation: In the above program, moon() is a non-member function and its prototype is declared at the beginning of the program. The function main() calls function moon(). In function moon(), object j of type class mem is declared and a member function earth() is invoked. Thus, non-member function calls the member function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset