8.28  THE main() FUNCTION AS A MEMBER FUNCTION

We know that the function main() is the starting execution point of every C/C++ program. The main() can be used as a member function of the class. But the execution of program will not start from this member function. The compiler treats member function main() and the user-defined main() differently. No ambiguity is observed while calling function. The following program narrates this concept.

 

8.36 Write a program to make main() as a member function.

#include<conio.h>

#include<iostream.h>

class A

{

public:

void main()

{

cout<<endl<<“In member function main()”;

}

};

int main()

{

clrscr();

A *a;

a->main();

return 0;

}

OUTPUT

In member function main()

Explanation: In the above program, class A is declared and has one member function main(). In the non-member function main(), the object a invokes the member function main() and a message is displayed as shown in the output.

8.29  OVERLOADING MEMBER FUNCTIONS

Member functions are also overloaded in the same fashion as other ordinary functions. We learned that overloading is nothing but a function is defined with multiple definitions with same function name in the same scope. The following program explains the overloaded member function.

 

8.37 Write a program to overload member function of a class.

#include<iostream.h>

#include<stdlib.h>

#include<math.h>

#include<conio.h>

class absv

{

public :

int num (int);

double num (double);

};

int absv:: num (int x)

{

int ans;

ans=abs(x);

return (ans);

}

double absv :: num (double d)

{

double ans;

ans=fabs(d);

return (ans);

}

int main()

{

clrscr();

absv n;

cout<<“ Absolute value of -25 is ”<<n.num(–25);

cout<<“ Absolute value of -25.1474 is ”<<n.num(–25.1474);

return 0;

}

OUTPUT

Absolute value of -25 is 25

Absolute value of -25.1474 is 25.1474

Explanation: In the above program, the class absv has a member function num(). The num() function is overloaded for integer and double. In function main() the object n invokes the member function num() with one value. The compiler invokes the overloaded function according to the value. The function returns the absolute value of the number.

8.30  OVERlOADING main() FUNCTIONS

In the last two subtitles, we learnt how to make main() as member function and how to overload member function. Like other member function, main() can be overloaded in the class body as a member function. The following program explains this concept:

 

8.38 Write a program to declare main() as a member function and overload it.

#include<conio.h>

#include<iostream.h>

class A

{

public:

void main(int i)

{

cout<<endl<<“In main (int) :”<<i;

}

void main (double f)

{

cout<<“ In main(double) :”<<f;

}

void main (char *s)

{

cout<<endl<<“In main (char ) : ”<<s;

}

};

int main()

{

clrscr();

A *a;

a->main(5);

a->main(5.2);

a->main(“C++”);

return 0;

}

OUTPUT

In main (int) :5

In main (double) :5.2

In main (char) : C++

Explanation: This program is same as the previous one. Here, the main() function is used as a member function and it is overloaded for integer, float, and character.

It is not possible to overload the non-member main() function, which is the source of the C/C++ program and hence the following program will not be executed and displays the error message “Cannot overload ‘main’”.

 

#include<iostream.h>

void main()

{ }

main (float x, int y)

{

cout<<x<<y;

return 0;

}

TIP

The main() is the only function that cannot be overloaded.

8.31  THE main(), MEMBER FUNCTION, AND INDIRECT RECURSION

When a function calls itself, then this process is known as recursion or direct recursion. When two functions call each other repetitively, such type of recursion is known as indirect recursion. Consider the following program and explanation to understand the indirect recursion using OOP. The program without using OOP is also described for programmers who are learning C++.

 

8.39 Write a program to call function main() using indirect recursion.

//Indirect Recursion Using OOP//

#include<iostream.h>

#include<conio.h>

int main (int);

class rec

{

int j;

public:

int f;

rec (int k, int i)

{

clrscr();

cout<<“[ ”;

f=i;

j=k;

}

~rec()

{ cout<<“] Factorial of number : ”<<f ; }

void pass()

{

cout<<main (j--)<<“ * ”;

}

};

rec a(5,1);

main (int x)

{

if (x==0)

return 0;

a.pass();

a.f=a.f*x;

return x;

}

OUTPUT

[ 0 * 1 * 2 * 3 * 4 * 5 ] Factorial of number : 120

Explanation: In the above program, class rec is declared with constructor, destructor, member function pass(), and two integer variables. The integer variable j is private and f is public. The function main() is defined with one integer argument. Usually, main() with arguments is used for the applications on the dos prompt. In this program, main() is called recursively by member function pass(). When a function call is made, the value of member data variable is decreased first and then passed. Thus, the main() passes value to itself. In function pass(), main() function is invoked and its return value is displayed. The public data member is directly used and by applying multiplication operation, factorial of a number is calculated.

Generally, objects are declared inside the function main(). But in this program function main() is used in recursion. Hence, if we put the object declaration statement inside the main(), in every call of main() object is created and the program will not run properly. To avoid this, the object is declared before main().

Constructor is used to initialize data members as well as to clear the screen. Destructor is used to display the factorial value of the number. All the statements that we frequently put in main() are written outside of main().

Before the class declaration, prototype of main() is given, because the member functions do not know about; and the prototype declaration provides information about main() to member function.

 

TIP

For C programmers the previous program in C style is explained as follows.

8.40 Write a program to call function main() using in-direct recursion in C style.

//Indirect Recursion in C style//

#include<iostream.h>

#include<conio.h>

#include<process.h>

int m=5;

int f=1;

int j;

main (int x)

{

void pass (void);

if (x==0)

{ clrscr();

cout<<endl<<“Factorial of number =”<<f;

return 0;

}

f=f*x;

pass();

return x;

}

void pass() { main (m--); }

OUTPUT

Factorial of number =120

Explanation: The logic of the program is same as the previous one. The user-defined function pass() has only one job to invoke function main(). The if conditions inside main() check the value of variable x. If value of x is zero, then if block is executed that displays factorial of the number and terminates the programs.

8.32  BIT FIELDS AND CLASSES

Bit field provides exact amount of bits required for storage of values. If a variable value is 1 or 0 we need a single bit to store it. In the same way, if the variable is expressed between 0 and 3, then the two bits are sufficient for storing these values. Similarly if a variable assumes values between 0 and 7, then three bits will be enough to hold the variable and so on. The number of bits required for a variable is specified by non-negative integer followed by a colon.

To hold the information, we use the variables. The variables occupy minimum one byte for char and two bytes for integer. Instead of using complete integer if bits are used, memory space can be saved. For example, to know the information about the vehicles, following information has to be stored in the memory:

  1. PETROL VEHICLE
  2. DIESEL VEHICLE
  3. TWO_WHEELER VEHICLE
  4. FOUR_WHEELER VEHICLE
  5. OLD MODEL
  6. NEW MODEL

In order to store the status of the above information, we may need two bits for the type of fuel as to whether the vehicle is of petrol or diesel type, three bits for its type as to whether the vehicle is two- or four-wheeler, and similarly, three bits for the model of the vehicle. Total bits required for storing the information would be 8 bits, that is one byte. It means that the total information can be packed into a single byte. Eventually bit fields are used for conserving the memory. The amount of memory saved by using bit fields will be substantial which is proved from the above example.

However, there are restrictions on bit fields when arrays are used. Arrays of bit fields are not permitted. Also the pointer cannot be used for addressing the bit field directly, although the use of the member access operator (->) is acceptable. The unnamed bit fields could be used for padding as well as for alignment purposes.

  1. Bits fields should have integral type. A pointer and array type is now allowed.
  2. Address of bit fields cannot be obtained using & operator.

The class for the above problem would be as follows:

 

class vehicle

{

unsigned type: 3;

unsigned fuel: 2;

unsigned model: 3;

};

The colon (:) in the above declaration tells to the compiler that bit fields are used in the class and the number after it indicates how many bits are required to allot for the field. A simple program is illustrated as follows:

 

8.41 Write a program to use bit fields with classes and display the contents of the bit fields.

#include<conio.h>

#include<iostream.h>

#define PETROL 1

#define DISEL 2

#define TWO_WH 3

#define FOUR_WH 4

#define OLD 5

#define NEW 6

class vehicle

{

private :

unsigned type : 3;

unsigned fuel : 2;

unsigned model :3;

public:

vehicle()

{

type=FOUR_WH;

fuel=PETROL;

model=NEW;

}

void show()

{

if (model==NEW)

cout<<“ New Model ”;

else

cout<<“ Old Model ”;

cout<<“ Type of Vehicle : ”<< type;

cout<<“ Fuel : ”<<fuel;

}

};

int main()

{

clrscr();

vehicle v;

cout<<“ Size of Object : ”<<sizeof(v)<<endl;

 

v.show();

return 0;

}

OUTPUT

Size of Object : 1

New Model

Type of Vehicle : 4

Fuel : 1

Explanation: In the above program, using #define macros are declared. The information about the vehicle is indicated with integers from 1 to 6. The class vehicle is declared with bit fields. The number of bits required for each member is initialized. As per the program, type of vehicle requires 3 bits, fuel requires 2 bits, and model requires 3 bits. An object v is declared. The constructor initializes bits fields with data. The output of the program displays integer value stored in the bit fields, which can be verified with macro definitions initialized at the beginning of the program.

8.33  NESTED class

When a class is defined in another class, it is known as nesting of classes. In nested class the scope of inner class is restricted by outer class. Simple programming example using public specifier is demonstrated for understanding.

 

8.42 Write a program to display some message using nested class.

#include<iostream.h>

#include<conio.h>

class one

{

public:

class two

{

public:

void display()

{

cout<< “Wonderful language C++ ”;

}

};

};

int main()

{

clrscr();

one::two x;

x.display();

return 0;

}

OUTPUT

Wonderful language C++

Explanation: In the above example, one class is nested in another; that is class two is nested in class one. By using scope resolution operator, the inner class member function is accessed and “Wonderful language C++” is displayed in the above program.

8.34  MORE PROGRAMS

8.43 Write a program to accept string and display the string. Use null character for determining the end of string.

#include<iostream.h>

#include<conio.h>

class text

{

char str[50];

public :

void get()

{

cout<<“Enter text : ”;

cin.getline(str,50);

}

show (int x)

{

if (str[x]==’’)

return 0;

else

{

cout<<str[x];

return 1;

}

}

};

int main()

{

clrscr();

int k=-1;

text s;

s.get();

cout<<“Entered text : ”;

while (s.show (++k));

return 0;

}

OUTPUT

Enter text : Object Oriented Programming Entered text : Object Oriented Programming

Explanation: In the above program, the class text is defined with one data member of character type. The get() function is used to read text through the keyboard. The show() function is defined with integer argument. The show() function displays the string character by character. The integer variable x shows the element number in the character array str[50]. The if statement checks whether the current character is null or other. If the character is null then it returns 0, otherwise it displays the character and returns 1. In function main(), s is an object of class text. The object s calls gets() and reads text.

The show() function is called within the bracket of while loop. The integer variable k is incremented before passing it to the function show(). In the statement, ++k increment first takes place and then incremented value is sent. The array element counting starts from zero. In order to display the string from first character, the initial value of k should be 0. Thus, initializing k to –1 and applying increment operator as prefix can do this.

We know that the while loop is executed till the given test condition evaluates to 1. Thus, till the function show() returns 1 the loop is executed and when it returns 0 the loop is terminated. The function show() returns 0 only when it reaches the end of text. Meanwhile, the entire text is displayed on the screen.

 

8.44 Write a program to enter two strings and concatenate them. Display the resulting string.      

#include<iostream.h>

#include<string.h>

#include<conio.h>

class text

{

char str1[15];

char str2[15];

char str3[30];

public :

 

void get()

{

cout<<“ Enter First String : ”;

cin.getline(str1,15);

cout<<“ Enter Second String : ”;

cin.getline (str2,15);

}

len()

{

return (strlen(str1));}

 

void show()

{

cout<<“ First String : ”<<str1;

cout<<“ Second Strng : ”<<str2;

cout<<“ Third String : ”<<str3;

}

combine (int x,int y)

{

str3[x]=str1[x];

if (x>=y)

str3[x]=str2[x-y];

if (str2[x-y]==’’)

return 0;

else

return 1;

}

};

int main()

{

clrscr();

int k=-1,y;

text s;

s.get();

y=s.len();

while (s.combine (++k,y));

s.show();

return 0;

}

OUTPUT

Enter First String : CPLUS

Enter Second String : PLUS

First String : CPLUS

Second String : PLUS

Third String : CPLUSPLUS

Explanation: In the above program, the class text has three character array data members, namely str1[15], str2[15], and str3[30], and has also four member functions, namely get(), len(), show(), and combine(). The get() function is used to read strings through the keyboard; the len() function returns the length of the first string; the show() function displays the strings; and the combine() function combines the first and second strings and assigns to the third string. The integer variable k is initialized to –1. The integer variable y contains the length of the first string. The function combine() is called within the bracket of while loop and two integers variable k and y are passed.

In combine() function, x indicates character element position in character arrays str3[] and str1[]. The statement str3[x]=str1[x] assigns characters of str1[] array-to-array str3[]. This assignment continuous till x >= y (y is length of the first string). When x is greater than y, the statement str3[x]=str2[x-y] is executed; that is, assignment of second string is now carried out.

The x-y displays the element number of second string. The second if statement in the combine() function checks whether the null character has met or not. If yes it returns 0, otherwise 1. The values 0 or 1 returned by combine() are collected by the while loop. The while loop is executed till it gets 1 from function combine(). When the combine() function returns 0, the while loop is terminated. The show() function after while loop displays all the strings.

 

TIP

The reader may be in confusion as to why so much effort is required to write simple programs in C++. We can easily solve these problems with very short codes in C. The objective is to master how to solve these problems using OO concepts and to make the reader think more on objects. In the previous examples, the reader might have noticed that even for a small task, it might be calculation or comparison, and for every task, we defined member functions. The class should provide every operation in the form of method or member function needed by objects and the object should not be dependent on main() or other non-member function for any requirement. This is the pure object-oriented programming.

8.45 Write a program to declare data member of a class as public. Initialize and display them without using function.

#include<iostream.h>

#include<conio.h>

class boy

{ public:

int weight;

float height;

};

int main()

{

clrscr();

boy raj, sonu;

raj.weight=35;

raj.height=4.5;

sonu.weight=30;

sonu.height=4.1;

cout<<“ Weight of Raj = ”<<raj.weight;

cout<<“ Height of Raj = ”<<raj.height;

cout<<“ Weight of Sonu = ”<<sonu.weight;

cout<<“ Height of Sonu = ”<<sonu.height;

return 0;

}

OUTPUT

Weight of Raj = 35 Height of Raj = 4.5

Weight of Sonu = 30 Height of Sonu = 4.1

Explanation: In the above program, the class boy contains two public members, namely weight and height. The members are public and can be accessed directly without using member function. In function raj and sonu are two objects of the class boy. The data elements of weight and height of both objects are initialized and displayed.

 

8.46 Write a program to declare constant member function arguments.

#include<iostream.h>

#include<conio.h>

class data

{

private :

int d;

public :

void set() { d=10; }

void show() { cout<<endl<<“d=”<<d; }

void sub (data const &a, data const &b)

{ d=a.d-b.d; }

};

int main()

{

clrscr();

data a,b,c;

a.set();

b.set();

c.sub(a,b);

c.show();

return 0;

}

OUTPUT

D=0

Explanation: In the above program, the arguments of function sub() are declared as constant. Hence, an attempt to modify these arguments will generate an error. Thus, by declaring the member variable arguments const, we can prevent them from modification.

 

8.47 Write a program to show the difference between private and public data members of a class.

#include<iostream.h>

#include<conio.h>

class player

{

private :

char name[20];

int age;

public :

float height;

float weight;

};

int main()

{

clrscr();

class player a;

// a.name =”Sanjay”; // not accessible

a.height=5.5;

a.weight=38;

cout<<“Height : ” <<a.height;

cout<<“ Weight : ” <<a.weight;

return 0;

}

OUTPUT

Height : 5.5

Weight : 38

Explanation: In the above program, a class player is defined with four member variables char name[20], int age, float height, and float weight. The first two members are private and last two members are public. In the function main(), a is an object of type class player. The public member variables of class player are height and weight initialized with 5.5 and 38, respectively, through object a. It is not possible to access the private member of the class directly. Hence, the variables name and age cannot be accessed. Any attempt to access them through the object will display an error message “player::name is not accessible” or “ player::age is not accessible”.

 

8.48 Write a program to initialize private and public member variables of the class. Display the contents of member variables.

#include<iostream.h>

#include<conio.h>

class num

{

int x;

float y;

 

public :

char z;

void readdata(int j, float k)

{

x=j;

y=k;

}

void display()

{

cout<<“x=”<<x <<“ y=”<<y;

}

};

int main()

{

clrscr();

class num j;

j.z=’C’;

j.readdata(10,10.5);

j.display();

cout<<“ z= ”<<j.z;

return 0;

}

OUTPUT

x=10 y=10.5 z= C

Explanation: In the above example, the class num contains private as well as public member variables. The two private member variables x and y are assigned values using member functions. The public member variable z is assigned directly in function main(). The variable j is an object, readdata() is a member function. The variables j and k are parameters to be passed. Consider the following statements.

 

  1. j.y=10.5 // invalid statement
  2. j.z=’C’ // valid statement

The statement (a) is invalid because member variable y is private whereas statement (b) is a valid because member variable z is public and accessible by the object of the same class.

8.34.1  Member Function Inside the class

8.49 Write a program to declare class with member variables and functions. Read and display the data using the member functions.

#include<iostream.h>

#include<conio.h>

class player

{

private :

char name[20];

int age;

float height;

float weight;

public:

void setdata()

{

cout<<“Enter Name Age Height Weight ”;

cin>>> name >>age >> height >> weight;

}

void show()

{

cout<<“ Name :” <<name;

cout<<“ Age :” <<age;

cout<<“ Height :” <<height;

cout<<“ Weight :” <<weight;

}

};

int main()

{

clrscr();

class player a;

a.setdata();

a.show();

return 0;

}

OUTPUT

Enter Name Age Height Weight

Sanjay 24 5.5 54

Name :Sanjay

Age :24

Height :5.5

Weight :54

Explanation: In the above program, the class player contains four private member variables and two public member functions setdata() and show(). The definition of both the functions is inside the class. In the previous example, we noticed that the object of any class could not access the private member variables of the class. To access the private member variables of the class, member function of that class are used. In this program, setdata() and show() are the member functions of class player. The setdata() function reads data through the keyboard and show() functions display the data on the screen. These member functions cannot be called directly as ordinary functions. Consider the statement a.setdata(). Here, a is an object of class player followed dot(.) operator and function name. An attempt to call these member functions directly without using object of that class will generate an error in the program such as “Function should have a prototype”.

In this program, function definition of the member function is inside the class. It is also possible to put prototype of the function inside the class and definition outside the class. While defining the function, it is necessary to specify class name followed by scope access operator. This declaration tells the compiler the relation between the class and the member function. For understanding this concept, the following program is illustrated as follows.

8.34.2  Member Function Outside the class

8.50 Write a program to declare class with member variables and functions. Read and display the data using the member functions. Declare function definition outside the class.

#include<iostream.h>

#include<conio.h>

class player

{

private :

char name[20];

int age;

float height;

float weight;

public:

void setdata();

void show();

};

void player :: setdata()

{

cout<<“Enter Name Age Height Weight ”;

cin>>> name >>age >> height >> weight;

}

void player :: show()

{

cout<<“ Name :” <<name;

cout<<“ Age :” <<age;

cout<<“ Height :” <<height;

cout<<“ Weight :” <<weight;

}

int main()

{

clrscr();

class player a;

a.setdata();

a.show();

return 0;

}

OUTPUT

Enter Name Age Height Weight

Ajay 24 5.2 45

Name :Ajay

Age :24

Height :5.2

Weight :45

Explanation: The above program is same as previous one. The only difference is that the function definition of the member functions is outside the class. The prototypes of these functions are inside the class, which are enough for these functions to join membership with class player.

Consider the following statements.

 

void player:: setdata()

Void player:: show()

Both these statements tell the compiler that the functions setdata() and show() are member functions of class player.

So far we declared the entire member functions as public. It is also possible to declare member functions as private. A private function can be called only from public member functions. Even an object of same class cannot access the private function. An example is illustrated below based on this idea.

8.34.3   Private Member Functions

8.51 Write a program to declare private member function and call this member function using another public member function.

#include<iostream.h>

#include<conio.h>

#include<math.h>

class num

{

private :

int x;

int sqr(int);

public:

input()

{

int n;

cout<<“Enter a Non-zero Number :”;

cin>>>n;

return sqr(n);

}

};

num :: sqr (int k)

{

return k*k;

}

int main()

{

clrscr();

int sq;

class num j;

sq=j.input();

cout<<“ Square of ”<<sqrt(sq) <<“ is ” <<sq;

// j.sqr(5); not accessible

return 0;

}

OUTPUT

Enter a Non-zero Number : 25

Square of 25 is 625

Explanation: In the above program, the function sqr() is declared as private and the function input() as public. The input() function reads an integer through the keyboard and calls the private function sqr(). The function sqr() calculates the square of the number and returns result to the input() function. The input() function again returns this value to the variable sq declared in main(). The last cout statement displays the entered number and its square. The statement given in remark is invalid statement, because an object cannot access private member. The input() public function acts as an inter-mediator in between private function and an object of the class. Without public functions, it is not possible for the object to access private functions.

 

8.52 Write a program to enter hours. Convert it into seconds and minutes. Display results.

#include<iostream.h>

#include<conio.h>

class hour

{

int hours;

int minutes;

int seconds;

public :

void input(void);

void show(void);

void convert();

};

void hour :: input()

{

cout<<“ Enter Hour: ”;

cin>>>hours;

}

void hour :: show()

{

cout<<“ Hour = ” <<hours <<“ Minute = ”<<minutes <<“ Second = ” <<seconds;

}

void hour :: convert()

{ minutes=hours*60;

seconds=minutes*60;}

main()

{ clrscr();

hour X,Z;

cout<<“ Object X”;

X.input();

X.convert();

cout<<“ X : ”;

X.show();

return 0;

}

OUTPUT

Object X

Enter Hour : 4

X : Hour = 4 Minute = 240 Second = 14400

Explanation: In the above program, the class hour is declared with three integer members and three member functions. The input() function reads number of hours through the keyboard. The function convert() calculates minutes and seconds and assigns results to minutes and seconds variables. The function show() displays the contents of all the member variables. In the function main(), X is an object of class hour. The object X calls all the member functions one by one. The values of member variables after execution are displayed at the output.

 

8.53 Write a program to count the number of vowels present in the entered string.

#include<stdio.h>

#include<iostream.h>

#include<conio.h>

#include<ctype.h>

#include<string.h>

struct vowels

{

private :

char str [20];

public :

void input()

{

cout<<“Enter text in small case : ”;

gets(str);

}

length()

{

int l=strlen(str);

return l;

}

vowel (int x)

{

if (str[x]==’a’ || str[x]==’e’ || str[x]==’i’ || str[x]==’o’ || str[x]==’u’)

{

cout<<“ ” <<str[x];

return 1;

}

else

return 0;

}

};

main()

{

clrscr();

int i,l,c=0;

vowels b;

b.input();

l=b.length();

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

{

c=c+b.vowel(i);

}

cout<<“ ”<<c<<“ Vowels are present in the string”;

return 0;

}

OUTPUT

Enter text in small case : Programming

o a i

3 Vowels are present in the string

Explanation: In the above program, instead of class keyword struct keyword is used. The struct vowels has only one member variable, which is a character array str. The function input() reads text through the keyboard and assigns it to the member variable str[20]. The function length() determines the length of the string. The function vowel() when called receives an integer from calling function. The if statement checks whether the (x) the character of the string is vowel or consonant. If it is one of the vowels, the function returns 1 otherwise 0.

In main(), b is an object of struct vowels. Using for loop, the object b calls the function vowel() repetitively. The return value (0 or 1) is added to a variable c during repetitive calls. The value of c finally displays the number of vowels present in the string.

 

8.54 Write a program to enter text. Find a given character in the string and replace it with another given character.

#include<stdio.h>

#include<iostream.h>

#include<conio.h>

#include<string.h>

class fandr

{

char str [40];

char f;

char r;

public :

 

void accept()

{

cout<<“ Enter text : ”;

cin.getline(str,40);

cout<<“ Find what (char) : ”;

f=getche();

cout<<“ Replace with (char) : ”;

r=getche();

}

void display (int d)

{

cout.put(str[d]);

}

len()

{ int l=strlen(str);

return(l);

}

void find ( int i)

{

if (str[i]==f)

replace(i);

}

void replace ( int k)

{ str[k]=r; }

};

main()

{

clrscr();

int i,l;

fandr b;

b.accept();

l=b.len();

cout<<“ Replaced text : ”;

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

{

b.find(i);

b.display(i);

}

return 0;

}

OUTPUT

Enter text : Progra__er

Find what (char) : _

Replace with (char) : m

Replaced text : Programmer

Explanation: In the above program, the class fandr have three character data type member variables. The function accept() reads the text through the keyboard. Here, the function cin.

getline(str, 40) is used to connect with the keyboard. The first argument is the name of array and second is size of array. Followed by this, the character to be traced and replaced is entered in variable f and r. The function len() is obviously used for calculating length of the string. The function find() receives an integer from calling function. The if statement checks whether the specified character by the integer is equal to a given character or not. If the character is found, the replace() function is called which replaces the traced character with value of ‘r’ variable. The for loop in main() function repetitively calls the functions find() and display(). Remember, the function replace() is called by find() function whenever the if condition is true. The cout.put() is used to display the character on the screen. Thus, find and replace operations execute.

 

8.55 Write a program to find largest out of ten numbers.

#include<iostream.h>

#include<conio.h>

#include<process.h>

class num {

int number[10];

public :

input (int i)

{

cout<<“ Enter Number (“<<i+1<<”) :” ;

cin>>>number[i];

return(number[i]);

}

void large ( int s, int m)

{

if (number[s]==m)

{

cout<<“ Largest number : ”<<number[s];

exit(1);

}

}

};

main()

{

clrscr();

int i,sum=0,k;

num b;

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

sum=sum+ b.input(i);

for (k=sum;k>=0;k--)

{

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

b.large(i,k);

}

return 0;

}

OUTPUT

Enter Number (1) :125

Enter Number (2) :654

Enter Number (3) :246

Enter Number (4) :945

Enter Number (5) :258

Enter Number (6) :159

Enter Number (7) :845

Enter Number (8) :940

Enter Number (9) :944

Enter Number (10) :485

Largest number : 945

Explanation: In the above program, the class num has one integer array as its member variable with element size 10 (number[10]). The input() function reads an integer through the keyboard and returns it to main() function. The first for loop repetitively calls function input(). The return value of input() function is added to variable sum. The second and third for loops together are used to find the largest number in the array. The second and third for loop variables are used as arguments for the function large(). As per iteration, the successive element numbers and decremented value of sum assigned to variable k. The values of variables k and loop variable i are sent to function large(). In each third for loop iteration, the second for loop executes once and value of sum is decremented. The if condition in large() function checks both the arguments. If the arguments are the same, the largest number is displayed, and the exit (1) function terminates the program, otherwise the program execution continues.

 

8.56 Write a program to count the numbers between 1 and 100, which are not divisible by 2,3, and 5.

#include<stdio.h>

#include<iostream.h>

#include<conio.h>

class div

{

static int num;

public :

void check(int n)

{

if (n%2!=0 && n%3!=0 && n%5!=0)

{

cout<<n <<“ ”;

num++;

}

}

void show()

{ cout<<endl <<“ Total numbers : ”<<num;}

void loop();

};

void div :: loop()

{

int x;

cout<<endl<<“ Numbers from 1 to 100 not divisible by 2,3 & 5 ”;

for ( x=0 ;x<=100;x++)

check(x);

}

int div :: num=0;

int main()

{

clrscr();

int x;

div d;

d.loop();

d.show();

return 0;

}

OUTPUT

Numbers from 1 to 100 not divisible by 2,3 & 5 1 7 11 13 17 19 23 29 31 37

41 43 47 49 53 59 61 67 71 73

77 79 83 89 91 97

Total numbers : 26

Explanation: In the above program, the class div is declared with one static data member variable, that is num. The class div also contains member functions check(), show(), and loop(). The function check() checks the received value with if statement whether it is divisible by 2, 3, and 5 or not. If it is not divisible, the number is displayed and the value of static data member num is incremented. The loop() function contains for loop and calls the function check() with one argument. The prototype of function is given inside the class and definition outside the function, because the member function with any loop defined inside the class cannot be expanded inline and will result in a warning message. The more applicable practice is to write the definition of this kind of function outside the class. The function show() displays the total number of numbers that satisfies the condition. The object d declared in function main() invokes the member functions loop() and show().

 

8.57 Write a program to generate the nth Fibonacci number by using recursion.

Fibonacci series:1 1 2 3 5 8 13

#include<iostream.h>

#include<conio.h>

class Fibonacci

{

public:

fib(int x)

{

      int f;

if(x==0)

return 0;

if(x==1)

return 1;

else

f=fib(x-1)+fib(x-2);

return f;

}

};

int main()

{

clrscr();

Fibonacci a;

int y;

cout<<“ Enter the number:”;

cin>>y;

cout<<“ Sum of Fibonacci numbers upto ”<<y<<“ is ”<<a.fib(y);

getch();

return 0;

}

Output:

Enter the number:7

Sum of Fibonacci numbers upto 7 is 13

SUMMARY
  1. A class in C++ is similar to structure in C. Using class or structure, a programmer can merge one or more dissimilar data types and a new custom data type can be created.
  2. In C++, classes and structures contain member variables and member functions in their declarations with private and public access blocks that restrict the unauthorized use. The defined classes and structures further can be used as custom data type in the program to declare objects.
  3. The private and public are new keywords in C++. The private keyword is used to protect specified data and functions from illegal use whereas the public keyword allows access permission.
  4. The member function can be defined as private or public inside the class or outside the class.
  5. To access private data members of a class, member functions are used.
  6. The difference between member function and normal function is that the normal function can be invoked freely, whereas the member function can be invoked only using the object of the same class.
  7. The static is a keyword 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.
  8. When a function is defined as static, it can access only static member variables and functions of the same class. The static member functions are called using its class name without using its objects.
  9. 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.
  10. An object of a class can be passed to the function as arguments like variables of other data type. When an object is passed-by-value, then this method is called as pass-by-value, whereas when reference of an object is passed to the function then this method is called as pass-by-reference.
  11. When classes are declared inside a function, then such classes are called as local classes. The local classes have access permission to global variables as well as static variables. The local classes should not have static data member and functions.
EXERCISES

(A) Answer the following questions

  1. Explain class and struct with their differences.
  2. Which operators are used to access members?
  3. Explain the uses of private and public keywords. How are they different from each other?
  4. Explain the features of a member function.
  5. What are static member variables and functions?
  6. How are static variables initialized? Explain with a statement.
  7. What are friend functions and friend classes?
  8. How are static functions and friend functions invoked?
  9. What do you mean by constant function?
  10. What are local classes?
  11. What is recursion?
  12. What are bit fields?
  13. List the keywords terminated with a colon with their use.
  14. Can member functions be private?
  15. What is the concept of data hiding? What are its advantages in applications?
  16. Is it possible to access private data members without using member function? If yes, explain the procedure with an example.
  17. What are static objects?
  18. What is the difference between object and variable?

(B) Answer the following by selecting the appropriate option

  1. The members of a class are by default
    1. private
    2. public
    3. protected
    4. none of the above
  2. class data members can be accessed by
    1. public member functions
    2. private member function
    3. both (a) and (b)
    4. none of the above
  3. The objects of class can directly access
    1. public members
    2. private members
    3. protected members
    4. all of the above
  4. The private data members can be accessed through functions declared under
    1. private section
    2. public section
    3. protected section
    4. all of the above
  5. The protected data members can be accessed by private and protected member functions using
    1. non-member functions
    2. public member functions
    3. directly by object
    4. scope resolution operator
  6. For data hiding, data are generally declared in
    1. private section
    2. public section
    3. both (a) and (b)
    4. none of the above
  7. class declaration provides
    1. data hiding
    2. abstraction
    3. encapsulation
    4. all of the above
  8. Member functions can be defined
    1. only inside the class
    2. only outside the class
    3. inside as well as outside class
    4. none of the above
  9. A class contains
    1. only data
    2. only functions
    3. data and functions
    4. neither data nor functions
  10. When a class is defined, memory allocation is done
    1. at the same time
    2. when objects are declared
    3. when functions are called
    4. when values are passed
  11. Private data are accessible to
    1. objects directly
    2. objects through public member functions
    3. main function
    4. none of the above
  12. Public data members and functions are accessible by
    1. objects directly
    2. private members
    3. external function
    4. both (a) and (c)
  13. Inline function is not possible when
    1. a function contains a loop
    2. goto statement exists
    3. both (a) and (b)
    4. none of the above
  14. Functions defined outside the class can be accessed using
    1. scope resolution operator
    2. logical operator
    3. reference
    4. arithmetic operator
  15. Inline function
    1. saves memory
    2. takes extra time
    3. executes slowly
    4. wastes memory
  16. An inline function
    1. duplicates code
    2. speeds up the execution
    3. both (a) and (b)
    4. neither (a) nor (b)
  17. When inline function is called
    1. control is passed to function
    2. function is executed directly
    3. function code is replaced at that point
    4. none of the above
  18. The public member function can access
    1. private data
    2. public data
    3. protected data
    4. all of the above
  19. Public data can be accessed by
    1. private member function
    2. public member function
    3. protected member function
    4. all of the above
  20. By default, all member functions defined inside the class are treated as
    1. inline function
    2. external functions
    3. main function
    4. none of the above
  21. An encapsulated object is often called as
    1. abstract data type
    2. abstract class
    3. both (a) and (b)
    4. neither (a) nor (b)
  22. When one member function is called inside another member function, it is called
    1. cascading functions
    2. referencing functions
    3. nesting member function
    4. none of the above
  23. static data member is stored in memory as
    1. only one copy
    2. number of copies
    3. two copies
    4. no copy
  24. When a variable is declared as static, it is
    1. initialized to one
    2. initialized to zero
    3. not initialized
    4. none of the above
  25. A static data member can be recognized
    1. inside scope of class
    2. outside the class
    3. in main() function
    4. in non-member function
  26. When a variable is declared as static, objects share
    1. common data
    2. different data
    3. no data
    4. none of the above
  27. A static variable is accessible only within
    1. class
    2. main() function
    3. non-member function
    4. none of the above
  28. The memory for static data member is allocated
    1. only once
    2. twice
    3. thrice
    4. number of times
  29. If count is a static data member and item is a class, then

    int item::count;

    what is the value of count initially?

    1. zero
    2. one
    3. no value
    4. cannot be determined.
  30. Initialization of static data member must be done
    1. inside the class
    2. right after class definition
    3. in main() function
    4. in member function
  31. Which static data member can be accessed by objects of the same class?
    1. private
    2. protected
    3. public
    4. none of the above
  32. A static member function can access
    1. only static member variable
    2. non-static member variable
    3. static as well as non-static variables
    4. only non-static member variable
  33. A static member function can be called by
    1. objects only
    2. class name and scope resolution operator
    3. object as well as class name and scope resolution operator
    4. none of the above
  34. A private static member function can be accessed by
    1. private static member function
    2. public static member function
    3. objects of class
    4. both (a) and (b)
  35. A non-member function that can access the private data of class is known as
    1. friend function
    2. static function
    3. member function
    4. library function
  36. The size of object is equal to
    1. total size of data variables
    2. total size of member functions
    3. both (a) and (b)
    4. none of the above
  37. The class without any data members or member functions is called as
    1. empty class
    2. non-empty class
    3. both a and b
    4. none of the above

(C) Attempt the following programs

  1. Write a program to declare a class with three integer public data variables. Initialize and display them.
  2. Write a program to declare private data member variables and public member function. Read and display the values of data member variables.
  3. Write a program to declare private data member and a function. Also declare a public member function. Read and display the data using private function.
  4. Write a program to declare three classes S1, S2, and S2. The classes have a private data member variable of character data type. Read strings for the classes S1 and S2. Concatenate the strings read and assign it to the data member variable of class S3.
  5. Write a program to enter positive and negative numbers. Enter at least 10 numbers. Count the positive and negative numbers using classes and objects.
  6. Write a program to declare class with private member variables. Declare member function as static. Read and display the values of member variables.
  7. Write a program to declare a class temp_ture as given below. Declare an array of five objects. Read and display the data using arrays.

    class temp_ture

    {

    private:

    char date[12], ct1[15], ct2[15], ct3[15], ct4[15];

    int temp [4]

    }

     

  8. Write a program to declare a class with two integers. Read values using a member function. Pass the object to another member function. Display the difference between them.
  9. Write a program to define three classes. Define a friend function. Read and display the data for three classes using common functions. Use friend functions.
  10. Write a program to define a local class. Also define global variables with the same name as that of member variables of class. Read and display the data for global and member variables.
  11. Write a program to generate Fibonacci series using recursion with member function.
  12. Write a program to overload a member function and display the string, int, and float using overloading function.
  13. Write a program to calculate sum of digits of an entered number using indirect recursion. Recursion should be between main() and member function.
  14. Write a program to display a string in reverse using recursion.
  15. Write a program to add numbers from 1 to 10.
  16. Write a program to find area of a right angle triangle.
  17. Write a program to compute area and perimeter of a square.
  18. Write a program to compute average marks obtained by a student in five subjects.
  19. Write a program to display even numbers from 1 to 10.
  20. Write a program to display numbers divisible by 5 between 1 and 100.
  21. Write a program to display numbers divisible by 11 and 3 between 1 and 100.
  22. Write a program to find area of a cube.
  23. Write a program to find negative and positive numbers of an array.

(D) Find the bugs in the following programs

  1. class data

    {

    private ;

    };

  2. class data

    {

    private:

    int x=20;

    }

  3. #include<iostream.h>

    #include<conio.h>

    class data

    { int x; };

    void main()

    { data A;

    A.x=30; }

  4. #include<iostream.h>

    #include<conio.h>

    class data

    { int x;

    public:

    void show(void);

    };

    void show() { cout<<“ In show()”; }

    void main()

    { data A;

    A.show(); }

  5. class

    {

    public:

    void print()

    { cout<<a; }

    };

    void main()

    {

    }

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

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