46
Prof.Manoj S. Kavedia (9860174297) ([email protected]) Class and Object Q1.What is class? How they are defined ?Describe them Ans. A class is a way to bind the data and its associated functions together. It allows the data (and functions) to be hidden, if necessary, from external use. When defining a class, we are a new abstract data type that can be treated like any other built-in data type. Generally, a class specification has two parts: 1. Class declaration 2. Class function definitions The class declaration describes the type and scope of its members. The class functions definitions describe below the class functions are implemented. The general form of a class declaration is: class class_name { private: variable declarations; //data members function declarations; //member function public: variable declarations; //data member function declaration; // member Function } ; The class declaration is similar to a struct declaration. The keyword class specifies, that what follows is an abstract data of type class_name. The body of a class is enclosed within braces and terminated by a semicolon. The class body contains the declaration of variables and functions. These functions and variables are collectively called class members. They are usually grouped under two sections, namely, private and public to denote which of the members are private and which of them are public. The keywords private and public are known as visibility labels. These keywords are followed by a colon. The class members that have been declared as private can be accessed only from within the class. On the other hand, public members can be accessed from outside the class also. The data hiding (using private declaration) is the key feature of object- oriented programming. The use of the keyword private is optional. By default, the members of a class are private. If both the labels are missing, then, by default, all the 2 2 Object and Classes Syllabus Specifying a class, Defining member functions, Arrays within a class, Creating objects, memory allocation for objects, static data & member function, Arrays of objects, objects as function argument. 1

Prof.Manoj S. Kavedia (9860174297) ([email protected]) Object …kavediasir.yolasite.com/resources/Chapter-2-Objects and... · 2012-05-29 · Prof.Manoj S. Kavedia (9860174297)

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Prof.Manoj S. Kavedia (9860174297) ([email protected])

Class and ObjectQ1.What is class? How they are defined ?Describe themAns. A class is a way to bind the data and its associated functions together. It allows the data (and functions) to be hidden, if necessary, from external use. When defining a class, we are a new abstract data type that can be treated like any other built-in data type. Generally, a class specification has two parts:

1. Class declaration2. Class function definitions

The class declaration describes the type and scope of its members. The class functions definitions describe below the class functions are implemented.The general form of a class declaration is:

class class_name{

private:variable declarations; //data membersfunction declarations; //member function

public:variable declarations; //data memberfunction declaration; // member Function

} ;

The class declaration is similar to a struct declaration. The keyword class specifies, that what follows is an abstract data of type class_name. The body of a class is enclosed within braces and terminated by a semicolon. The class body contains the declaration of variables and functions. These functions and variables are collectively called class members. They are usually grouped under two sections, namely, private and public to denote which of the members are private and which of them are public. The keywords private and public are known as visibility labels. These keywords are followed by a colon.

The class members that have been declared as private can be accessed only from within the class. On the other hand, public members can be accessed from outside the class also. The data hiding (using private declaration) is the key feature of object-oriented programming. The use of the keyword private is optional. By default, the members of a class are private. If both the labels are missing, then, by default, all the

22Object and Classes

SyllabusSpecifying a class, Defining member functions, Arrays within a class, Creating objects, memory allocation for objects, static data & member function, Arrays of objects, objects as function argument.

1

Prof.Manoj S. Kavedia (9860174297) ([email protected])

members are private. Such a class is completely hidden from the outside world and does not serve any purpose.

The variables declared inside the class are known as data members and the functions are known as member functions. Only the member functions can have access to the private data members and private functions. However, the public members (both functions and data) can be accessed from outside the class.

Q2.What are the different ways member function can be defined?Ans. Member functions can be defined in two places:

• Outside the class definition.• Inside the class definition.

Irrespective of the place of definition, the function should perform same task. Therefore, the code for the function body would be identical in both the cases. However, there is a subtle difference in the way the function header is defined.

Q3.What is scope resolution operator ?state its functionAns. The symbol :: is called the Scope Resolution Operator.

The scope resolution operator (::) in C++ is used to define the already declared member functions (in the header file with the .cpp or the .h extension) of a particular class. In the .cpp file one can define the usual global functions or the member functions of the class.

To differentiate between the normal functions and the member functions of the class, one needs to use the scope resolution operator (::) in between the class name and the member function name i.e. ship::foo() where ship is a class and foo() is a member function of the class ship.

The other uses of the resolution operator is to resolve the scope of a variable when the same identifier is used to represent a global variable, a local variable, and members of one or more class(es). If the resolution operator is placed between the class name and the data member belonging to the class then the data name belonging to the particular class is referenced.

If the resolution operator is placed in front of the variable name then the global variable is referenced. When no resolution operator is placed then the local variable is referenced.Example

#include <iostream>int n = 12; // A global variableint main() { int n = 13; // A local variable cout << ::n << endl; // Print the global variable: 12 cout << n << endl; // Print the local variable: 13}

Q4. Describe how to access the class member (data member and member function)Ans.The class body contains the declaration of variables and functions. These functions and variables are collectively called class members. They are usually grouped under two sections,

2

Prof.Manoj S. Kavedia (9860174297) ([email protected])

1. private and 2. public

To denote which of the members are private and which of them are public. The keywords private and public are known as visibility labels. These keywords are followed by a colon.

PrivateThe class members that have been declared as private can be accessed only from

within the class. Public

public members can be accessed from outside the class also.

As described above private data members of the class can be accessed through the public member functions only of the same class.

Object_name.function_name(actual_arguments)Is the syntax of accessing the data member of the class.

Following example is used to demonstrate the same#include<iostream.h>#include<conio.h>class rectangle{ private : int len, br; public: void area_peri( )

{int a, p;a = len * br;p = 2 * (len +br);cout<<endl<<"Area = "<<a;cout<<endl<<"Perimeter = "<<p;

}

void getdata ( ){

cout<<endl<<"Enter length and breadth ";cin>>len>>br;

}void setdata (int l, int b )

{len = l;br = b;

} void displaydata( )

{cout<<endl<<"length = "<<len;cout<<endl<<"breadth = "<<br;

3

Prof.Manoj S. Kavedia (9860174297) ([email protected])

}};

//………………Main Program…………………….. void main( ){

rectangle r1,r2,r3; //define 3 objects of class rectangler1.setdata(10,20); //set data in elements of the objectr1.displaydata( ); //display the data set by setdata( )r1.area_peri( ); // calculates and print area and Perimeterr2.setdata(5,8); r2.displaydata( ); r2.area_peri( ); r3.getdata( ); //receive data from keyboard r3.displaydata( ); r3.area_peri( );

}

Q5.What do you mean by the term data member and member Function?Ans. The variables declared inside the class are known as data members and the functions are known as member functions. Only the member functions can have access to the private data members and private functions. However, the public members (both functions and data) can be accessed from outside the class. Example

class class_name{

private:variable declarations; //data membersfunction declarations; //member function

public:variable declarations; //data memberfunction declaration; // member Function

} ;

4

Prof.Manoj S. Kavedia (9860174297) ([email protected])

Q6.List some of the header files used in C++?Ans.

Q7.Differentiate between object and classesAns.Classes and objects are separate but related concepts. Every object belongs to a class and every class contains one or more related objects.

1. A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don't change.

2. The class to which an object belongs is also (usually) static. If a particular object belongs to a certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed.

3. An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change.

SrNo Classes Object1 Class is template or Object is software construct which binds

5

Prof.Manoj S. Kavedia (9860174297) ([email protected])

blueprint , its states how object should be and Behave

data and logic or methods /functions together

2 Class is user defined data type

Object is run time entity of class

3. Class cannot be passed as argument or parameter

Object can be passed as argument or parameter

4. Class is group of a object that share common property

Object is real time entity of class

5. Class can define object Object cannot define class6. Example

Class Demo { int num; public void getData(int x) { num = x ; } public void display() { cout <<“\n Number = “<<num); } };

ExampleDemo D1 = new Demo(); Demo D2 = new Demo(); Demo D3 = new Demo();

Q8.Differentiate between data encapsulation and data abstractionAns.Following are the difference between encapsulation and Abstraction

1. Encapsulation is hiding the details of the implementation of an object so that there are no dependencies on the particular implementation.

2. Abstraction is removing some distinctions between objects, so as to showing their commonalities

3. Encapsulation is wrapping data into single unit (eg. class) 4. Abstraction is hiding unessential parts and showing only essential data.

(eg. student class- name, age are essential parts while height, weight are not essential, so hiding information of height and weight)

Q9.Differentiate between inheritance and PolymorphismAns.

Polymorphism1.Polymorphism can be defined as ability more than one form.2.Here different function as same name.3.Types are Run-time polymorphism & Compile-time polymorphism.4.It can work with one class also.

6

Prof.Manoj S. Kavedia (9860174297) ([email protected])

5.Supports both overloaded functionsas well as overrided functions.

5.Supports only overloaded functions.

Q10.State the necessity of preprocessor directive? State importance of #include<iostream.h>?Ans. A C++ (or C) compiler begins by invoking the preprocessor, a program that uses special statements, known as directives or control statements, that cause special compiler actions such as:

file inclusion, in which the file being preprocessed incorporates the contents of another file, exactly as if the included file’s text were actually part of the including file;

macro substitution, in which one sequence of text is replaced by another; conditional compilation, in which parts of the source file’s code can be eliminated

at compile time under certain circumstances.All preprocessor directives begin with the # symbol (known as pound or hash), which

must occur in the leftmost column of the line. A preprocessor directive that takes up more than one line needs a continuation symbol, n (backslash), as the very last character of every line except the last.

Following directive #include<iostream.h> is used in the program. This directive causes the preprocessor to add the content of the iostream file to the program. It contains declaration for the identifier cout and the operator <<.

iostream is a header file which is used for input/output in the C++ programming language. It is part of the C++ standard library. The name stands for Input/Output Stream. In C++ and its predecessor, the C programming language, there is no special syntax for streaming data input or output. Instead, these are combined as a library of functions.

iostream provides basic input and output services for C++ programs. iostream uses the objects cin, cout, cerr, and clog for sending data to and from the standard streams input, output, error (unbuffered), and error (buffered) respectively. As part of the C++ standard library, these objects are a part of the std namespace.

Q11.How does a main() function of c++ differ from that of main() in C?Ans.In c++ main() returns an integer type value to the operating system.Therefore every main() in c++ should end with return(0) statement.other wise warning or an error might occur.Since main() returns an integer type value, return type for main() is explicitly specified int. Note that the default return type for all function in c++ is int. The following main without type return will run with warning.

main() { ------ ------}

Q12.Write C++ program to define member Function inside the class?Ans. #include<iostream.h>

#include<conio.h>Class DemoNumber

{7

Prof.Manoj S. Kavedia (9860174297) ([email protected])

private :int num; //Data Member

public :void getNumber() // Member Function inside Class

{cout<<”\n Enter the Number =”;cin>> num;

}void dispData()

{cout<<”\n Number = “+Num;

}}

void main(){

DemoNumber Dn1;Dn1.getNumber();Dn1.dispData();getch();

}

Q13.What is nesting of member function and Demonstrate using C++ functionAns. We know that a member function of a class can be called only by an object of that class using a dot operator. However, there is an exception to this. A member function can be called by using its name inside another member function of the same class. This is known nesting of member functions. Program below illustrates this feature.Program

#include <iostream.h>Using namespace std;class set

{int m, n;public:

void input(void); void display(void); int largest(void);

};int set :: largest (void)

{if(m >= n)

return (m);else

return (n);}

Void set :: input (void){

8

Prof.Manoj S. Kavedia (9860174297) ([email protected])

Cout<<“Input values of m and n \n” ;Cin >> m >> n;

}void set :: display (void)

{cout << “Largest value = “ <<largest()<<”\n”;

}

int main(){ set A;

A. input();A.display();return 0;

}Array

Q14.Explain how an array can be used in c++ ? Ans. There are essentially two ways to declare arrays in C++: statically and dynamically. The method you utilize in your program will depend on how you intend to use the array.

1. Static Array are using arrays and2. Dynamic arrays are using pointers

The following C++ statement declares a static array of 10 integers:

int my_array[10];

The data type int (short for integer), tells the compiler the size for each array element. The name of the array is my_array. An array name can be any valid C++ identifier. The number appearing between the brackets tells the compiler how many contiguous memory locations need to be reserved.

The name of the array, in this case my_array, is a constant pointer that points to the first element, or element 0, of my_array. Another way to access the first element of my_array is to use an index value of 0 along with the array index operator [ ]. The following statement assigns the value of 100 to the first element in my_array:

my_array[0] = 100;

To assign the value 100 to my_array elements 2 through 10 you could do the following:

my_array[1] = 100; my_array[2] = 100; my_array[3] = 100; my_array[4] = 100; my_array[5] = 100; my_array[6] = 100; my_array[7] = 100;

9

Prof.Manoj S. Kavedia (9860174297) ([email protected])

my_array[8] = 100; my_array[9] = 100;

Luckily the number appearing between the brackets doesn't have to be a numeric literal. It can be a valid identifier that represents an integer value. This could be either a variable, a constant, or an expression that evaluates to an integer value. For example, a faster way of initializing all the elements of my_array to 100 would be to declare an integer variable, set its value to 0, use it to index my_array, then increment the variable by one and repeat the process until all the elements were set to 100. The following C++ code will do exactly that:

for(int i = 0; i<10; i++) my_array[i] = 100;

Following two examples show how arrays can be used in c++ functionExample : Program to illustrates processing of an Array

#include<iostream.h>#include<conio.h>void main( ){

double A[3]; // Array Declaration

// Stores Data in Arrayclrscr();A[2] = 22.22;A[0] = 11.11;A[1] = 33.33;

//Read Data from an Array cout << " A[0] = "<<A[0]<<endl;cout << " A[1] = "<<A[1]<<endl;cout << " A[2] = "<<A[2]<<endl;getch( );

}

Example: Program to illustrates processing of an Array#include<iostream.h>#include<conio.h>void main( ){

const int SIZE = 5; //defines the size N for 5 elementsint A[SIZE] ; // declares the array's elements as type integercout<<"\n Enter "<<SIZE<<" Numbers : \t" ;for ( int i = 0; i < SIZE; i++)

{ cin>>A[i];}

cout<<"\n In Reverse Order : ";10

Prof.Manoj S. Kavedia (9860174297) ([email protected])

for( i = SIZE - 1; i >= 0 ; i--){

cout<<"\t"<<A[i];}

getch( );}

Q15.Write C++ program to read and Display array of 100 elements Ans. /* Program to read 100 element and display them */

#include<iostream.h>#include<conio.h>void main( ){

const int SIZE = 100; //defines the size N for 100 elementsint Arr[SIZE] ; // declares the array's elements as type integer

cout<<"\n Enter "<<SIZE<<" Numbers : \t" ;for ( int i = 0; i < SIZE; i++)

{ cout<<”\n Enter the data for A[”<<i+1<<”]=”; cin>>Arr[i];}

cout<<"\n Content of the Array are as Follows : ";for( i =0; i <=SIZE-1 ; i++)

{cout<<"\nA[“<< i+1 << "]=” <<A[i];

} getch( );}

Q16.Write Program to illustrate Passing Array Elements to a Function Ans.Example : Program to illustrate Passing Array Elements to a Function

#include<iostream.h>#include<conio.h>void show( int ) ;void main( ){

int number[ ]= { 11, 22, 33, 44, 55 } ;for( int i = 0; i <= 4; i++)

show(number[i]); //passing element of an array to the functiongetch( );

}void show(int x)

{11

Prof.Manoj S. Kavedia (9860174297) ([email protected])

cout<<"\t"<<x;}

Q17.Write a Program to illustrates Two-dimensional ArrayAns. Program to illustrates Two-dimensional Array

#include <iostream.h>#include <conio.h>void main( ){

int emp[4][2] ;int i ;for ( i = 0; i <=3 ; i++)

{cout<<"\n Enter Employee No. and Salary : ";cin>>emp[i][0]>>emp[i][1];

} cout<<"\n Emplyoee Number \t Salary ";

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

cout<<"\n"<<emp[i][0]<<"\t\t"<<emp[i][1];}

getch( );}

Q18.Write the Program to illustrates, Initializing a Two-Dimensional ArrayAns. Program to illustrates, Initializing a Two-Dimensional Array

#include <iostream.h>#include <conio.h> void main ()

{ int i , j ; int digits[4][3] = { {0,1,2},{3,4,5},{6,7,8},{9,10,11} } ; cout<<"\n The digits are :\n" ; for (i=0 ; i<4 ; i++) { for (j=0 ; j<3 ; j++) cout<<" \n "<<digits[i][j] ; } getch () ;

}

Q19.Write to Program to illustrates, Initializing a Two-Dimensional ArrayAns.Program to illustrates, Initializing a Two-Dimensional Array

#include <iostream.h>#include <conio.h>

12

Prof.Manoj S. Kavedia (9860174297) ([email protected])

void main ( ){

int i , j ; char letters[6][1] = { {'M'},{'i'},{'c'},{'k'},{'e'},{'y'} } ; cout<<"\n The letters are :\n" ; for (i = 0, j = 0 ; i < 6 ; i++)

cout<<letters[i][j] ; getch ( ) ;

}

Q20.Write the Program that adds up the individual elements of 2 D ArrayAns.Example : Program that adds up the individual elements of 2 D Array

#include <iostream.h>#include <conio.h>void main ( ){

int i , j , sum ; int elements[3][7] = { {0,2,4,6,8,10,12},

{14,16,18,20,22,24,26}, {28,30,32,34,36,38,40} } ;

for ( i = 0,sum = 0 ; i < 3 ; i++) { for (j=0 ; j<7 ; j++) sum = sum + elements[i][j] ; } cout <<"\n The result of addition = "<< sum ; getch ( ) ;

}

Q21.Write Program that display average of marks for each subjectAns.Example : Program that display average of marks for each subject#include <iostream.h>#include <conio.h>void main ( )

{int i , j ;int marks[3][5] ={ {65,68,75,59,77},

{62,85,57,66,80}, {71,77,66,63,86} } ;

float avg ;cout<<" \n\t\t ";for (i = 0 ; i < 5 ; i++)

cout<<"subj"<<i+1<<"\t";

cout<<"\n" ;13

Prof.Manoj S. Kavedia (9860174297) ([email protected])

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

cout<<" student"<<i+1<<"\t";for(j=0 ; j<5 ; j++)

cout<<marks[i][j]<<"\t";cout<<" \n ";

}cout<< "\n\nThe Average of each subject is : \n" ;

for (j=0 ; j<5 ; j++){

cout<<"Subject"<<j+1<<" : " ;

for (i=0,avg=0 ; i<3 ; i++)avg = avg + float(marks[i][j]) ;

avg = avg / 3 ; cout.precision(2);

cout<<avg<<"\n";}getch () ;

}

Q22.Write C++ program to sort an array of 100 elementsAns.. Program to read 100 element and display them

#include<iostream.h>#include<conio.h>void main( ){

const int SIZE = 100; //defines the size N for 100 elementsint Arr[SIZE] ; // declares the array's elements as type integerint i , j , temp;//Reading the array cout<<"\n Enter "<<SIZE<<" Numbers : \t" ;for ( i = 0; i < SIZE; i++)

{ cout<<”\n Enter the data for A[”<<i+1<<”]=”; cin>>Arr[i];}

//Sorting the Array

for ( i = 0; i < SIZE; i++){for ( j = 0; j < SIZE-1; j++)

{ if ( Arr[j] >= Arr[j+1])

14

Prof.Manoj S. Kavedia (9860174297) ([email protected])

{temp = Arr[j];Arr[j] = Arr[j+1];Arr[j+1] = temp;

}

}}

//Displaying the content of the arraycout<<"\n Content of the Sorted Array are as Follows : ";for( i =0; i <=SIZE-1 ; i++)

{cout<<"\nA[“<< i+1 << "]=” <<A[i];

} getch( );}

Q23.Write C++ program to find maximum number from an array of 100 elementsAns.

#include<iostream.h>#include<conio.h>void main( ){

const int SIZE = 100; //defines the size N for 100 elementsint Arr[SIZE] ; // declares the array's elements as type integerint i , j , max;//Reading the array cout<<"\n Enter "<<SIZE<<" Numbers : \t" ;for ( i = 0; i < SIZE; i++)

{ cout<<”\n Enter the data for A[”<<i+1<<”]=”; cin>>Arr[i];}

//Finding maximum from the array

for ( i = 0; i < SIZE; i++){

max = Arr[0];for ( j = 1; j < SIZE-1; j++)

{ if ( max < Arr[j])

{max = Arr[j];

}

}15

Prof.Manoj S. Kavedia (9860174297) ([email protected])

}

//Displaying the content of the arraycout<<"\n Maximum from 100 elements = : "<< max;

getch( );}

Default argument Function

Q24.What is Default argument function ?Describe it with exampleAns. In computer programming, a default argument is an argument to a function that a programmer is not required to specify. In most programming languages, functions may take one or more arguments. Usually, each argument must be specified in full (this is the case in the C programming language)

C++ allows us to call a function without specifying all its arguments. In such cases, the function assigns a default value to the parameter which does not have a matching argument in the function call. Default values are specified when the function is declared. The compiler looks at the prototype to see how many arguments a function uses and alerts the program for possible default values. Here is an example of a prototype (i.e. function declaration) with default values:.

int MyFunc(int a, int b, int c=12);This function takes three arguments, of which the last one has a default of twelve. The programmer may call this function in two ways:

result = MyFunc(1, 2, 3);result = MyFunc(1, 2);

In the first case the value for the argument called c is specified as normal. In the second one, the argument is omitted, and the default value of 12 will be used instead.

There is no means to know if the argument has been specified by the caller or if the default value was used.Also important point is that always trailing arguments can have default values.Defaut argument are to be added from right to left only.We cannot provide default argument value in middle of the argument list.

int add(int a , int b , int c=20); // legal declarationint add(int a =20 , int j); // illegal declarationint add(int a , int b=30, int c); // illegal declarationint add(int a=2 , int j =3 , int c); // illegal declaration

ExampleClass Simple_Interest

{int principle_Amount;float rate_of_interest;int numer_of_year;float sint;

public :void getData(int pa , int noy , int ri=0.115)

{principle_Amount = pa;rate_of_interest = ri;

16

Prof.Manoj S. Kavedia (9860174297) ([email protected])

number_of_year = noy;}

void calculate(){sint = )principle_Amount * rate_of_interest * number_of_year)}

void display(){

cout <<”\n Principle Amount =”<< principle_amount ;cout<<”\n Rate of interest = “<<rate_of_interest;cout<<”\n Number of year = ”<< number_of_year;cout<<”\n Simple Interest = “<<sint;}

};

void main(){

Simple_Interest si1 , si2;si1.getData(1000,5);si2.getData(5000,3,0.135);si1.calculate();si2.calculate();cout<<”\n Simple Interest for object-1”;si1.display();cout<<”\n Simple Interest for object-2”;si2.display();getch();

}

ExplanationIn above example object si1 uses default argument for rate of interest , since it is

not specified in the fucntion during call.In this case rate of interest is 11.5% which is defined as default argument.

In above example object si2 does not uses default argument for rate of interest , since it is specified in the fucntion during call.In this case rate of interest is 13.5% which is defined as defualt argument.

Q25.List the characteristics of the member functionAns.Following are the characteristics of the member function1.Same Name of the member function can be used in many different classes2.Private data can be accessed by the member functions only3.Member function can call another member function without dot operator.

Q26.What is object? How it is created?Ans.Objects are basic run time entities in an object oriented system. They may represent a person, a place, a bank account that a program must handle. They may also be a

17

Prof.Manoj S. Kavedia (9860174297) ([email protected])

user defined functions such As vectors, date and time. Program object should be chosen such that they match closely the real World object eg. Elements of computer user environment are windows, menus and graphics, objects.

The physical objects are automobile in graphics stimulation, electronic component in circuit designing. The match between programming objects and a real world objects is a good resulting Objects offering the revolution in programming.For example : students objects includes the data members and functions as given:

Objects : studentData :

Roll-on NameDate of birth

Functions :Total( ) Average( )Percentage( )

This variable is known as object. This variable will be the type of class declared. To create at object you need to write

Classname objectname;

in the function main()

After creating objectname object, all data members are member functions declared in class gets initialised and member functions can be called with the statement

objectname.function();

For Example – this is class Class student

{ private :int roll;int mark1, mark2;float average;

public:void getData()

{ ---------- }void calculate()

{------------}void displayData()

{------------}}

Declaration of ObjectStudent S1 , S2[10] , *S3 ;S1 is object of class student.S2[100] is array of 10 object of class student.S3 is pointer to an object of class student.

18

Prof.Manoj S. Kavedia (9860174297) ([email protected])

Another way of Declaring ObjectObject can also be declared or defined by just placing their names immediately

after closing brace of class ie in the following wayClass employee

{------------------------------

} e1 , e2[10] , *e3;

Q27.List and describe the access specifiers used in OOPAns.The access specifiers used in OOP are as follows

1. public2. private3. protected

Private The members are accessible only by the member functions or friend functions.

Protected These members are accessible by the member functions of the class and the classes which are derived from this class.

Public Accessible by any external member.

Access control helps prevent you from using objects in ways they were not intended to be used. This protection is lost when explicit type conversions (casts) are performed.The default access to class members (members of a class type declared using the class keyword) is private; the default access to struct and union members is public. For either case, the current access level can be changed using the public, private, or protected.

Access Specifier in More detailsPrivate

• Can be data or method members • Are accessible ONLY through other methods of the same class where they are

declared • Cannot be accessed through a class instance • Will not be inherited

Public• Can be data or method members • Are accessible globally from any function/method outside the class they are

declared, across the application • Are accessible ONLY through a valid instance of the class in which they are

declared

19

Prof.Manoj S. Kavedia (9860174297) ([email protected])

Protected• Can be data and method members • Exactly same as private members for all practical purposes, except for the

inheritance part • These members are inherited by a child of the class in which they are declared • Their behaviour in the child class depends on how the inheritance has been

defined • If the inheritance is private, these are private in the child class, if it is public,

these are public in the child class, and if the inheritance in protected, these are protected in the child class thus allowing further inheritance.

Nesting of Member Function

Q28.What is Nesting of Member function describe with help of programAns. A member function of a class. Can be called only by an object of that class using a dot operator. A member function can be called by using its name inside another member function of the same class. This is known as nesting of member function.

# include <iostream.h>class circle{ int r1 ; public :

void getdata ( ){

cout << “Enter radius” ;cin >> r1 ;

} int area_circle()

{ int a ;

a = 3.14 × r1 × r1 ;return (a) ;

}

void putdata ( ){cout << “ Area of circle =” << area_circle () ;}

} ;void main ( )

{circle c1 ;

20

Prof.Manoj S. Kavedia (9860174297) ([email protected])

c1 . getdata ( ) ;c1 . putdata ( ) ;

}Q29.Explain with diagram how memory allocation is done for an objectAns. An object is a combination of data member and member function. It might given an impression that when an object of particular class is created memory is allocated to both its data member and member function. This is partially true. When an object is created memory is allocates to the data member only and not to member function.

Actually the member function are created place in memory space only once when they are define as a part of class specification. Since all the objects belonging to that class are the same member function, no separate space is created.

However separate storage is allocated for every object data member since they contain different value it allows different object to handle their data in a manner that suits them.

The member functions are created and placed in the memory function only once when they are defined as a part of class. Since all objects are belonging to that class use the same member function & no separate memory is allocated for the member function of each object. When the objects are created only space for memory variables is allocated separately for each object i.e the member variables will hold different data values for different object as shown in the fig.

Class abc{

int a;int b;

public:void getdata( );void disp( );} a1, a2;

Static Data member and Member function

Q30.Explain what is static data member ? what are the characteristics of static data memberAns. Static Member variables are generally used to maintain values common to the entire class. Static Members are stored separately rather than as a part of an object. As they are associated with the class itself rather than with any class objects, they are also known as class variables.A static data member has certain special characteristics :

a. It is initialized to zero, when the first object of its class is created. b. No other initialization to such member is permitted.

display getdata

Common for all objects , memory allocated to function where defined

A2 object

a

bX

A1 object

a

bX

21

Prof.Manoj S. Kavedia (9860174297) ([email protected])

c. Only one copy of that member is created for the entire class and is shared by all object at that class.

d. It is visible only within the class.The syntax to define static data member is as follows :

class item{

public: static int count;

};

int item::count = 0; // definition outside class declaration

Static data members are not part of objects of a given class type; they are separate objects. As a result, the declaration of a static data member is not considered a definition. The data member is declared in class scope, but definition is performed at file scope.

Q31.Write C++ program to implement the working of static data membersAns . Definition out side the class as shown in the example.

Class record{

static int count;public:

void counter(){ count++;}

void disp();{

cout<<count;}

};

int record::count;void main()

{ record r1,r2,r3; r1.counter(); r1.disp(); r2.counter(); r2.disp(); r3.counter(); r3.disp();

}

output1223

Count

r1 r2 r3

22

Prof.Manoj S. Kavedia (9860174297) ([email protected])

The type and scope of each static member variables must be define outside the class as given in above example.

Count is initialize to 0. when first object r1 is created. The count is increment each time when the counter function is called. Since there is only one copy of all data shared by all the objects as given below.

While defining static variables some initial value can also be defined to variables by defining

int record::count=10;After execution of above program if count is initialized to 10. then output will be

11121213

Q32.Why static variables are called as class variableAns.Static Member variables are generally used to maintain values common to the entire class. Static Members are stored seperately rather than as a part of an object. They are associated with the class itself rather than with any class objects and therefore they are also known as class variables.

Q33.Explain what is static member function ? what are the characteristics of static member FunctionAns. Static Member Functions : Similar to static data members, a member function can also be defined as static. A member function that is declared static has the characteristics as follows

1. It can have access to only static members (functions or variables) declared in the same class.

2. To call static member function we need to write statement with the name of class.classname : : functionsname;

The statements written in the definition of static function can be invoked and variables defined, processed in it are having seperate copies of objects and can hold unique value for that object.

Q34.Write C++ program to implement the working of static members function Ans. class record

{ static int count;

public:static void counter();

{count++;cout<<count;

}};int record::count=10;void main(){

record r1,r2;

23

Prof.Manoj S. Kavedia (9860174297) ([email protected])

record :: counter();record :: counter();

}

Array of Objects

Q35.How an array of object can be created demonstrate with c++ programAns.Similar to Array of structure in C, we also can have array of variables (objects) that are of type class. Naturally, these variables are known as arrays of objects.As we create the object using class name, we need to write array variable name along with size of array along with class name.

Consider a following example : class product{

char model[20];float price;

public;void readdata();void dispdata();

};This is a class with name product, to create array of this class type, we can

write.product telephones[10]; or product entertainment[5];

Graphical representation telephone(0) telephone(1) ------- telephone(9)model price model price ------- model modelreadata() dispdata() readata() dispdata() ------- readata() dispdata()

So the array telephones with their respective prices.To access array values, we have to use usual array handling techniques. And to

connect it with object we can use telephone[i].model

and to call function we may write telephone[i].readdata();

An array of objects is stored inside the memory similar to n-dimensional array is C. Here also, the space for data items of the objects is created and member functions are stored separately and will be shared by all objects.

Array of Class Objects Class objects one similar to any other C++ data type in that you can declare

pointer to them and arrays of them.

The array notation is the same as that of an array of structures.

24

Prof.Manoj S. Kavedia (9860174297) ([email protected])

Program : Array of Objects

#include <iostream.h>#include <string.h>/*----------------------Class definition-----------------------*/

class student{

int roll_no;char name[20];

public : // prototypes declaredvoid set_data(int, char *);void print_data();

};

void student::set_data(int c, char *s){

roll_no = c;strcpy(name, s);

}void student::print_data()

{cout << "Roll No. : " << roll_no << "\t";cout << "Name : " << name << "\n\n";

}

/*--------------------Definition ends here-------------------*/void main(void)

{student array[10]; // Array of Objects declaredint i;char names[10][10] = {"kush", "stavan", "poonam", "sachi", "samarth", "hetal", "trupti", "simone", "shalaka", "megha"};

// accessing member of an object where the object is an array element

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

array[i].set_data(i, names[i]);}

cout << "The data output is :\n\n";for (i=0; i<10; i++)

{array[i].print_data();

}getch();

}25

Prof.Manoj S. Kavedia (9860174297) ([email protected])

Object as Argument to Function

Q36.Describe how an object can be passed argument to functionAns. The functions are subprograms, written along with main() program and we can pass values from main() program to these subprogram to get processed. These values are of primary data type in C, and built-in datatype in C++.As C++ is best supporter of Object Oriented Programming techniques, here object may be passed as argument to the function. This particular process can be done in two ways

1.A copy of the entire object is passed to the function.

2.Only the address of the object is transferred to the function.

The method of passing copy of object is known as pass-by-value in this case, if the changes are made to object after called in function, then there is no effect on original object.

The second method is known as call-by-reference. In this case, the address of object is passed, to the function, as argument. If any changes are made that directly reflects the original object but this method avoids duplication of object. This method is more efficient.

Q37.Write C++ program to implement Object as function argument?Ans. Example Objects as Function Arguments -by reference

#include <iostream.h>#include<conio.h>

class Rational{

int numerator;int denominator;

public : void set(int, int); // prototypes declaredvoid print();void exchange (Rational*);

};void Rational::set(int a, int b)

{

26

Prof.Manoj S. Kavedia (9860174297) ([email protected])

numerator = a;denominator = b;

}

void Rational::print(){

cout << numerator << " / " << denominator;cout << "\n";

}

void Rational::exchange(Rational *n1){

int temp = 0;temp=numerator;numerator=(*n1).numerator;(*n1).numerator=temp;temp=denominator;denominator=(*n1).denominator;(*n1).denominator=temp;

}

void main(void){

Rational a, b;clrscr();a.set(2,5);b.set(3,7);a.exchange(&b); // Objects passed as argumentscout << "a = "; a.print();cout << "b = "; b.print();getch();

}

Q38.Write C++ program to implement Object reference as function to argument?Example : Objects as Function Arguments -by value

#include <iostream.h>#include<conio.h>class Rational{

int numerator;int denominator;

public : void set(int, int); // prototypes declaredvoid print();void sum (Rational, Rational);

};void Rational::set(int a, int b)

27

Prof.Manoj S. Kavedia (9860174297) ([email protected])

{numerator = a;denominator = b;

}void Rational::print()

{cout << numerator << " / " << denominator;cout << "\n";

}void Rational::sum(Rational n1, Rational n2) // n1,n2 are objects

{ int temp = 0;temp += n1.numerator * n2.denominator;temp += n1.denominator * n2.numerator;

numerator = temp;denominator = n1.denominator* n2.denominator;

}void main(void)

{Rational a, b, c;clrscr();a.set(2,5);b.set(3,7);c.set(0,0);c.sum(a,b); // Objects passed as arguments-by valuecout << "a = "; a.print();cout << "b = "; b.print();cout << "c = "; c.print();getch();

}InLine Function

Q39.What is inline function? Give it syntax? Write code to demonstrate inline code?Ans. One of the objectives using function in a program is to save memory space. When a function is likely to be called a number of times in the program, a lot of extra time in executing a series of instruction such as jumping to the function, saving registers, pushing arguments into the stack and returning to the calling function out . when a function is small, a substantial percentage of execution may be spent in such overheads. One solution to this problem may be to use macro definition known as the pre processor macro. The major drawback of macro is that they are not really function and therefore error checking does not occur at the time of compilation.

C++ has different solutions i.e. a new feature called as inline function. This is a function expanded in one line and when it is invoked. In inline function the error checking is possible. It also has a return type. & the compiler replaces this function call with the corresponding function code instead of jumping to the function memory location.Syntax

Inline <return type> function name (arg)28

Prof.Manoj S. Kavedia (9860174297) ([email protected])

{ //function definition

}example

inline int cube(int r){

return(r*r*r);}

On execution of this statement the values of called program.i.e double c= cube (3);Every time when a function is called the value of ‘C’ is 27. It’s far superior to the macros.

The benefits of inline function dimensions as the function grow inside that is if the statement definition is too long the compiler will treat as normal function.

Q40.List the situations were inline expansion may not workAns. It may not work for the following expansion.

1. Functions returning values if the loop or goto exists.2. If the function contains static variable.3.If inline functions are recursive.4.If they contain return statement though defined as ‘void’ function.(A void function can

have return statement)

Q41.Describe how function defined outside the class can be made INLINE. Demonstrate with program code.Ans.One of main objective of OOP is to separate the details of implementation from the class definition.It is therefore good practice to define the member function outside the class.

One can define a member function outside the class definition and still make it inline by just using the keyword or qualifier inline in the header line if the function definition.It is as demonstrated in the program below

Example/* Inline Member Functions */#include <iostream.h>#include<conio.h>

/*----------------------Class definition-------------------------*/class sample{

int a;public :

// inline member functionsvoid setdata(int x){ a = x;}void print_square()

{cout << "sqr(a) = " << a*a << "\n";

29

Prof.Manoj S. Kavedia (9860174297) ([email protected])

}

void print_cube();};

// inline member function

inline void sample::print_cube(){

cout << "cube(a) = " << a*a*a << "\n";}/*----------------------Definition ends here---------------------*/

void main(void){

clrscr();sample num;

num.setdata(10);num.print_square();num.print_cube();getch();

}

ExplanationThe member function print_cube() is made inline by writing keyword inline before

the function header in the definition. Function Returning Objects

Q42.How an Function return an object? Explain with the help of c++ programAns.A function as it receives the object as argument it can even return object as argument.Following example demonstrate the how function return the objectExample

class Summing{

private :int inum;float fnum;

public :void getInput(int x , float y )

{inum = x ;fnum =y ;

}Summing add(Summing S1 , Summing S2)

{Summing S3;S3.inum = S1.inum + S2.inum;S3.fnum = S1.fnum + S2.fnum;

30

Prof.Manoj S. Kavedia (9860174297) ([email protected])

Return(S3);}

void dispData(){

cout<< “ Integer = “<<inum <<”\t”;cout<<” Float =”<<fnum<<”\n”;

}};

void main(){

Summing sum1 , sum2 , sum3;sum1.getInput(20 , 40.5);sum2.getInput(40 , 80.5);sum3 = sum3.add(sum1 , sum2);sum1.dispData();sum2.dispData();sum3.dispData();getch();

}

ExplanationIn the main program object sum3 is accepting the values of the object return by

the function add. The return type of the function add is Object and it accepts two argument as object ie why it is written like these

Summing add(summing s1, summing s2){

summing sum3;------------------------------------return(Sum3);

}Hence the function add accepts the argument a object and returns argument as object.

Sample Program Based on Object and ClassesProgram-1 : create a class time having data member hours, minutes, seconds. Its member function are to initialize the object to display the time in proper format. I.e. HH:MM:SS add two timings & display the resultant time.

Class time{ int hh,mm,ss;

public:void getd(int h, int m, int s)

{ hh=h, mm=m, ss=s;

}void disp()

{ cout<<hh<<”:”<<mm<<”:”<<ss; }time add(time t1, time t2)

31

Prof.Manoj S. Kavedia (9860174297) ([email protected])

{ time t;t.ss=t1.ss+t2.ss;t.mm=t1.mm+t2.mm+t.ss/60;t.ss=t.ss%60;t.hh=t1.hh+t2.hh+t.mm/60;t.mm=t1.mm+t2.mm+1; }

return t;}};void main()

{ int r;r.getd();r.disp();getch(); }

Create a class distance having data members feet & inches add two distance & display the resultant distance in proper format. Initialize the objects with proper feets & inches.

Class distance{

int feet,inch;public:void getd(int f, int I)

{feet=f;inch=I;

}void display()

{ cout<<””<<inch<<””;

}distance cal(distance a, distance b)

{distance t;int i=0;t.inch=a.inch+b.inch;while(t.inch>12)

{t.inch=t.inch-12;i++;

}t.feet=a.feet+b.feet;return(t);

}};void main()

{distance a,b,c;a.getd(10,10);b.getd(5,10);c=c.cal(a, b);c.disp();

}

32

Prof.Manoj S. Kavedia (9860174297) ([email protected])

Output16’ 8”

Program-2Maintain the record of students and give the total marks for 3 subjects and calculate the average for each student and displays the contents on screen.

#include <stdio.h>#include <string.h>struct class {

int roll_no;char name[15];int m1, m2, m3;

} c[10];main( )

{int total, I;float avg;

for(I=O; I<=9; I++){ printf(“\n enter roll no, name and marks of three subjects for %d student=”); scanf(“%d %s %d %d %d %d”, &roll _no, &name[I], &m1[I], &m2[I], &m3[I]); }

for (I=0; I<=9; I++){total=c[I]m1 + c[I]m2 + c[I]m3;avg = total / 3;printf(“\n roll no=%d name=%s marks of three subjects= %d %d %d total=%d avg=%f”,roll_no[I],c[I].name, c[I].m1, c[I].m2, c[I].m3, total, avg);}

getch( );}

Although it is normal practice to place all the data members in private section in member function in public section. But some situation may require certain function hidden in main function such as detecting an account number in customer file or increase the salary of employee are events of serious consequences.Such function should be restricted from the outside access.

Class emp{

int ecode;char name[10];float sal;void update sal();

public:void input();void disp();

return(cir)}e1;

33

Prof.Manoj S. Kavedia (9860174297) ([email protected])

If e1 is the object of an class employee. e1.update sal(); //illegal

It can only be called within input or display function. Void input(){ update sal();}

program-3Create the class item having the data members item_code,item_name,& price initialize these values using getdata function. Display only those item codes having price more than 100.

Class item{

private:int item_code;char item_name[20];int price;

public:void getdata(int x,int y[], int z){

item_code=x;strcpy(item_name,y);price=z;

}}item q[10];void main(){ int I,a,b,char.c[20];

for(i=0;i<=9;i++){ cout<<”Enter the item_code”;

cin>>a; cout<<”Enter the item name”; cin>>c; cout<<”Enter the price of item”; cin>>b;item q[I].getdata(a,b,c);

}for(I=0;I<=9;I++){

if(item q[I].price>=100)cout<<item q[I].item_code<<” “<<item q[I].item_name<<” “<<item q[I].price<<endl;

}}

Programs as in Board Exams34

Prof.Manoj S. Kavedia (9860174297) ([email protected])

1. Write a program to find length of the string without using strlen() function Ans. /* program to find length of string without string length function */

#include<iostream.h>#include<conio.h>void main() { char *str; //declaring the string

cout << “\nEnter the string =”;cin>>str;

// repeat the loop till Null character is foundfor (int len =0 ; *name!=’\0’;len++);

cout << “\n String =” <<str;cout<<”\n Length of String = “<<len;getch();

}

2. Write a program to declare a class student containing data member’s roll number, name and percentage of marks. Read data for 2 students and display data of the student having higher percentage of marks.

Ans.Class student

{private :

char *name;int roll , mark1 , mark2;float per;

public :void getStudent()

{ cout << “\n Enter the name =” ;

cin>>name;cout << “\n Enter the Roll No.=”;cin>>roll;cout << “\nEnter two Subject Marks=”;cin>>mark1 >>mark2;

}

float calculate(){ per = (mark1 + mark2)/2.0 ; return (per);}

void display(){ cout <<”\n Name =”<<name; cout<<”\n Roll Number =”<<roll;

35

Prof.Manoj S. Kavedia (9860174297) ([email protected])

cout<<”\n Mark1 = “<< mark1; cout<<”\n Mark2 = “<<mark2; cout <<”\n Percentage =”<<per;}

};void main()

{student s1 , s2;s1.getStudent();s2.getStudent();if (s1.calculate() > s2.calculate())

{ cout<<”\n Student S1 has Highest marks=”; s1.display();}

else{ cout<<”\n Student S2 has Highest marks=”; s2.display();}

getch();}

3. Declare a class simple interest having data member as pricniple amount ,rate of interest , number of year.The function will have default value of rate of interest as 11.5%.Accept this data for two object.Calcualte and display simple interest for each object

Ans.Class Simple_Interest

{int principle_Amount;float rate_of_interest;int numer_of_year;float sint;

public :void getData(int pa , int noy , int ri=0.115)

{principle_Amount = pa;rate_of_interest = ri;number_of_year = noy;}

void calculate(){sint = )principle_Amount * rate_of_interest * number_of_year)}

void display(){

cout <<”\n Principle Amount =”<< principle_amount ;36

Prof.Manoj S. Kavedia (9860174297) ([email protected])

cout<<”\n Rate of interest = “<<rate_of_interest;cout<<”\n Number of year = ”<< number_of_year;cout<<”\n Simple Interest = “<<sint;}

};

void main(){

Simple_Interest si1 , si2;si1.getData(1000,5);si2.getData(5000,3);si1.calculate();si2.calculate();cout<<”\n Simple Interest for object-1”;si1.display();cout<<”\n Simple Interest for object-2”;si2.display();getch();

}

4. Write a program to declare a class rectangle having data member length and breadth.Accept this data form one object and display area and perimeter of rectangle

Ans./* Program to find area of rectangle & Perimeter */#include<iostream.h>#include<conio.h>class rectangle{ private : int len, br; public: void area_peri( ); //prototype declaration, to be defined

void getdata ( ){

cout<<endl<<"Enter length and breadth ";cin>>len>>br;

}void setdata (int l, int b ){

len = l;br = b;

} void displaydata( )

{cout<<endl<<"length = "<<len;cout<<endl<<"breadth = "<<br;

}37

Prof.Manoj S. Kavedia (9860174297) ([email protected])

};//………………Member Function Definition…………………void rectangle :: area_peri( ){

int a, p;a = len * br;p = 2 * (len +br);cout<<endl<<"Area = "<<a;cout<<endl<<"Perimeter = "<<p;

}//………………Main Program…………………….. void main( ){rectangle r1,r2,r3; //define 3 objects of class rectangler1.setdata(10,20); //set data in elements of the objectr1.displaydata( ); //display the data set by setdata( )r1.area_peri( ); // calculates and print area and Perimeterr2.setdata(5,8); r2.displaydata( ); r2.area_peri( ); r3.getdata( ); //receive data from keyboard r3.displaydata( ); r3.area_peri( ); }

5. Write a program to declare class time having data member as hrs , min , sec. write a constructor to accept data and use display function for two object

Ans.Class Time

{private :

int hrs , min , sec;public :

Time(){ cout << “\n Enter the Hours =” ;

cin>>hrs;cout << “\n Enter the Minute =”;cin>>min;cout << “\nEnter the seconds =”;cin>>sec;

}

void displayTime(){ cout <<”\n Time in HH:MM:SS Format”; cout<<hrs<<”:”<<min<<”:”<<sec;}

38

Prof.Manoj S. Kavedia (9860174297) ([email protected])

};void main()

{Time t1 , t2;t1.getTime();t2.getTime();cout<<”\n Time for Object-1”;t1.displayTime();cout<<”\n Time for Object-2”;t2.displayTime();

getch();}

6. Write a program to declare a class ‘student’ consisting of data members Stud_name and Roll no. Write the member functions accept () to accept and display ( ) to display the data for four students.

Ans. Class student{

private :char *name;int roll

public :void getStudent()

{ cout << “\n Enter the name =” ;

cin>>name;cout << “\n Enter the Roll No.=”;cin>>roll;

}

void display(){ cout <<”\n Name =”<<name; cout<<”\n Roll Number =”<<roll;}

};void main()

{student s1 , s2 , s3 , s4;; s1.getStudent();s2.getStudent();s3.getStudent();s4.getStudent();

s1.display();s2.display();

39

Prof.Manoj S. Kavedia (9860174297) ([email protected])

s3.display();s4.display();getch();

}7. Write program to calculate area of square and area of rectangle.Ans.

Void SquareArea(int s){

float area;area = s * s ;cout <<”\n Side =”<<s;cout <<”\n Area =”<<area;

}Void SquareRectangle(int le , int br )

{float area;area = le * br ;cout <<”\n Length=”<<le;cout <<”\n Breadth =”<<br;cout <<”\n Area =”<<area;

}

Void main(){

int side;int len , bre;SquareArea(10);SquareRectangle(10,20);getch();

}

8. Write C++ program two read two numbers and find sum, diff., product and division using different member function for each.

Ans.class operations

{int num1 , num2;public:

void getNumbers(int n1, int n2){

num1 = n1;num2 = n2;

}void Addition()

{int num3;

40

Prof.Manoj S. Kavedia (9860174297) ([email protected])

num3 = num1 + num2;cout<<”\n Sum = “<<num3;

}

void Subtraction() {

int num3;num3 = num1 - num2;cout<<”\n Difference = “<<num3;

}void Multiplication()

{int num3;num3 = num1 * num2;cout<<”\n Multiplciation = “<<num3;

}void Division()

{float num3;num3 = num1 / num2;cout<<”\n Division = “<<num3;

}};

void main(){ operations op1 ; op1.Addition(100,200); op1.Subtraction(200 , 50); op1.Multiplication(100,20); op1.Division(50,4); getch();}

9. Write a program to declare a class ‘Book’ having data-members as book-name, price and no. of pages. Accept this data for 2 objects and display name of book having greater price.

Ans.Class Book

{private :

char *bname;int page;float price;

public :void getBook()

{ cout << “\n Enter the Book name =” ;

cin>>bname;41

Prof.Manoj S. Kavedia (9860174297) ([email protected])

cout << “\n Enter the number of pages =”;cin>>page;cout << “\nEnter the price of book=”;cin>>price;

}

float calculate(){ return (price);}

void display(){ cout <<”\n Book Name =”<<bname; cout<<”\n Price of Book =”<<price; cout<<”\n Number of Pages = “<< page;}

};void main()

{Book b1 , b2;b1.getBook();b2.getBook();if (b1.calculate() > b2.calculate())

{ cout<<”\n Price of Book 1 is more”; b1.display();}

else{ cout<<”\n Price of Book 2 is more”; b2.display();}

getch();}

Board Question Chapter WiseWinter 2007

a. What is class ? Give examples.Ans.Refer Q.No.b. How memory is allocated when multiple objects of a class are created ? Explain

with suitable example.Ans.Refer Q.No.c. Can we create object of one class in definition of other class?Explain with suitable

example?Ans.Refer Q.No.d. Write a program to find length of the string without using strlen() function Ans.Refer Q.No.

42

Prof.Manoj S. Kavedia (9860174297) ([email protected])

e. Write a program to declare a class student containing data members roll number, name and percentage of marks. Read data for 2 students and display data of the student having higher percentage of marks.

Ans.Refer Q.No.

f. Explain difference between structure and class with exampleAns.Refer Q.No.

g. Find the errors from the following code.Rectify the codeClass Complex{

int real , imaginary;public :

void complex();void readdata();void showdata();

}

void main(){

complex c1;c1.ReadData();c1.DisplayData();

}Ans.Refer Q.No.

Summer 2008a. Define class with syntaxAns.Refer Q.No.

b. How many ways we can define member function in class? Give its syntax.Ans.Refer Q.No.

c. Declare a class simple interes having data member as pricniple amount rate of interest , number of year.The constructor will have default value of rate of interest as 11.5%.Accept this data for two object.Calcualte and display simple interest for each object

Ans.Refer Q.No.

d. Write a program to declare a class rectangle having data member length and breadth.Accept this data form one object and display area and perimeter of rectangle

Ans.Refer Q.No.

e. Write a program to declare class time having data member as hrs , min , sec. write a constructor to accept data and use display function for two object

Ans.Refer Q.No.

43

Prof.Manoj S. Kavedia (9860174297) ([email protected])

f. Describe memory allocation for objectAns.Refer Q.No.

Winter 2008a. Define inline function. Write its syntax. Give example.Ans.Refer Q.No.

b. Define friend function. Give example.Ans.Refer Q.No.

c. How to define a member function outside the body of class.Ans.Refer Q.No.

d. Comment on the following statement if display ( ) is a static member function of a class student, can it be called in the following way.

i. Student Sl ;ii. S1.display()

Ans.Refer Q.No.

e. Explain how friend function used to overload binary operatorAns.Refer Q.No.

f. Write a program to declare a class ‘student’ consisting of data members Stud_name and Roll no. Write the member functions accept ( ) to accept and display ( ) to display the data for four students.

Ans.Refer Q.No.

g. Explain arrays of objects with exampleAns.Refer Q.No.

Summer 2009a. Define class and object. Give example.Ans.Refer Q.No.

b. Write syntax for defining member function outside the class definition.Ans.Refer Q.No.

c. Write program to calculate area of square and area of rectangle.Ans.Refer Q.No.

d. Write C++ program two read two numbers and find sum, duff., product and division using different member function for each.Ans.Refer Q.No.

e. Explain the concept object as function argumentAns.Refer Q.No.

44

Prof.Manoj S. Kavedia (9860174297) ([email protected])

Winter 2009a. When do we declare a member of a class static?Ans.Refer Q.No.

b. How is member function of a class defined?Ans.Refer Q.No.

c. Define class and object also give example.Ans.Refer Q.No.

d. Describe the mechanism of accessing data members and member functions in the . following cases.

(i) Inside main program(ii) Inside a member function of same class(iii) Inside a member function of another class.

Ans.Refer Q.No.

e. Describe memory allocation for objectsAns.Refer Q.No.

Summer 2010Define the term object. Ans.Refer Q.No.Ans.Refer Q.No. a. How to define member. Function outside body of class.Ans.Refer Q.No.

b. Write a program to declare a class ‘Book’ having data-members as book-name, price and no. of pages. Accept this data for 2 objects and display name of book having greater price.

Ans.Refer Q.No.

c. Write output of following code. # include <iostream.h>

Class Emp{ int eno;

char name [20];Float salary;

};Void main

{Emp e;

Cout < size of (Emp) << “ \ n”<<sizeof(e );}

Ans.Refer Q.No.

d. State characteristics of static data member.Ans.Refer Q.No.

45

Prof.Manoj S. Kavedia (9860174297) ([email protected])

46