[go: up one dir, main page]

0% found this document useful (0 votes)
11 views23 pages

C++ Programming: Arrays in C++ 1) One Dimensional Array

Uploaded by

helps7025
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views23 pages

C++ Programming: Arrays in C++ 1) One Dimensional Array

Uploaded by

helps7025
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Computer Science ( D9) : XII - Paper –I

C++ PROGRAMMING
ARRAYS IN C++
1) ONE DIMENSIONAL ARRAY
An array (Linear) is a series of elements of the same type (Homogenous data elements)
placed in contiguous memory locations that can be individually referenced by adding an
index number to a unique identifier.
That means that, for example, we can store 5 values of type int in an array without having
to declare 5 different variables, each one with a different identifier. Instead of that, using an
array we can store 5 different values of the same type, int for example, with a unique
identifier.
For example, an array to contain 5 integer values of type intcalled NUMcould be represented
like this:

Where, each blank panel represents an element of the array, that in this case are integer
values of type int. These elements are numbered from 0 to 4 since in arrays the first index
is always 0, independently of its length.
Like a regular variable, an array must be declared before it is used. A typical declaration for
an array in C++ is:
Syntax: data_typearray_name[subscripted Value];
wheredata_type is a valid type (like int, float...), array_name is a valid identifier and
the elements field (which is always enclosed in square brackets [], specifies how many of
these elements the array has to contain and it should be +ve integer number or variable.)
Therefore, in order to declare an array called NUM as the one shown in the above diagram it
is as simple as:
int NUM [5];

INITIALIZING ARRAYS:
When we declare an array, we have the possibility to assign initial values to each one of its
elements by enclosing the values in braces { }. For example:
int NUM [5] = { 16, 2, 77, 40, 12071 };
This declaration would have created an array like this:
1) The amount of values between braces {} must not be larger than the number of
elements that we declare for the array between square brackets [].

P a g e | 38
Computer Science ( D9) : XII - Paper –I

2) When an initialization of values is provided for an array, C++ allows the possibility of
leaving the square brackets empty []. In this case, the compiler will assume a size for
the array that matches the number of values included between braces {}:

int NUM[] = { 16, 2, 77, 40, 12071 };


// arrays example Output:
#include <iostream.h>
#include<conio.h>
void main () Total = 12206
{
intnum [] = {16, 2, 77, 40, 12071};
int n, result=0;

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


{
result += num[n];
}
cout<<”Total =”<< result;
}

Solve Problem: 1) print the content of array in reverse order 2) Sort the content of
array in ascending/descending order using Bubble Sort method.

CHARACTER ARRAY:
The strings are in fact sequences of characters; we can represent them also as plain arrays of
char elements.
For example, the following array:
charst [20];
is an array that can store up to 20 elements of type char. It can be represented as:

Therefore, in this array, in theory, we can store sequences of characters up to 20 characters


long. But we can also store shorter sequences. For example, stcould store at some point in a
program either the sequence "Hello" or the sequence "Merry christmas", since both
are shorter than 20 characters.
Therefore, since the array of characters can store shorter sequences than its total length, a
special character is used to signal the end of the valid sequence: the null character, whose
literal constant can be written as '\0' (backslash, zero).
Our array of 20 elements of type char, calledst, can be represented storing the characters
sequences "Hello" and "Merry Christmas" as:

P a g e | 39
Computer Science ( D9) : XII - Paper –I

Notice how after the valid content a null character ('\0') has been included in order to
indicate the end of the sequence. The panels in gray color represent char elements with
undetermined values.
INITIALIZATION OF NULL-TERMINATED CHARACTER SEQUENCES
Because arrays of characters are ordinary arrays they follow all their same rules. For example, if we want to
initialize an array of characters with some predetermined sequence of characters we can do it just like any other
array:
charmyword[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
In this case we would have declared an array of 6 elements of type char initialized with the
characters that form the word "Hello" plus a null character '\0' at the end.
But arrays of char elements have an additional method to initialize their values: using string
literals.
For example, cin and cout support null-terminated sequences as valid containers for
sequences of characters, so they can be used directly to extract strings of characters from cin
or to insert them into cout. For example:
// null-terminated sequences of characters Please, enter your first name: John
#include <iostream.h> Hello, John!
void main ()
{
char question[] = "Please, enter your first
name: ";
char greeting[] = "Hello, ";
charyourname [80];
cout<< question;
cin>>yourname;
cout<< greeting <<yourname<<"!";
}
Solve problem:
1) Convert upper case string into lower case and vice versa
2) Count number of words and characters in the string

Hint: (0-255 ASCII characters: A/a -26+26, no.-10,sysmbols-32,control char-34, graphic char-128)
A->65--Z->90;a->97—z->122

P a g e | 40
Computer Science ( D9) : XII - Paper –I

POINTERS and REFERENCES:


Def: Pointer is a variable which holds the memory address of another variable. The
pointer has the following advantage:
1) It allows to pass variables, array, functions, strings, and structure as function
arguments (parameters).
2) It provides functions which can modify their calling arguments.
3) It supports dynamic allocation and de-allocation of memory segments.
4) With the help of a pointer, variable can be swapped without physically moving them
A pointer variable consists of two parts namely i) the pointer operator and ii) the address
operator.
1. POINTER OPERATOR:
A pointer operator can be represented by a combination of * (asterisk) with a variable. The
general format of the pointer declaration is:
data_type *pointer_variable;
For example: int *ptr;
2. ADDRESS (REFERENCE) OPERATOR:
An address operator can be represented by a combination of & (ampersand) with a
pointer variable. As soon as we declare a variable, the amount of memory needed is
assigned for it at a specific location in memory (its memory address).
The address that locates a variable within memory is what we call a reference to that
variable.
For example: p1 = &x; // means store the address of x in the pointer variable p1.
Now have a look at this code:
// my first pointer
#include <iostream.h>
#include<conio.h>
void main ()
{
int X=10, Y=20;
int *ptr1,*ptr2;
ptr1 = &Y;
ptr1 = &X
cout<<”X =”<<X<<” Y = “<<Y<<” “<<ptr1<<” “<<ptr2<<*ptr1<<*ptr2;
ptr2=ptr1; // address ptr1 assign to ptr2
cout<<”X =”<<X<<” Y = “<<Y<<” “<<ptr1<<” “<<ptr2<<*ptr1<<*ptr2;
*ptr1= *ptr2; // value of *ptr2 assign to *ptr1
cout<<”X =”<<X<<” Y = “<<Y<<” “<<ptr1<<” “<<ptr2<<*ptr1<<*ptr2;
}
Output :
1) 10 20 1003 1004 10 20
2) 10 20 1003 1003 10 10
3) 10 20 1003 1003 10 10

P a g e | 41
Computer Science ( D9) : XII - Paper –I

POINTERS TO FUNCTIONS:
Q. What is Call by reference? What is the advantage of call by reference over call by value?
1. Call by value and Call by reference
// call by Value // function Define // call by reference USING // define function
#include void swap(int X, int Y) POINTER void swap(int *X, int *Y)
<iostream.h> { #include {
#include<conio.h> int T; <iostream.h> int T;
void main () T=X #include<conio.h> T = *X
{ X= Y; void main () *X= *Y;
void swap(int ,int) Y = T; { *Y = T;
int A, B; } void swap(int * ,int *) }
cout<<”Enter the value of A int A, B;
and B”; cout<<”Enter the value of
cin>> A >> B; A and B”;
cin>> A >> B;
cout<<”Before swap the
content of A and B are “ cout<<”Before swap the
<<A <<B; content of A and B are “
<<A <<B;
swap(A , B);
swap(&A ,& B);
cout<<”After swap the
content of A and B are “ cout<<”After swap the
<<A <<B; content of A and B are “
getch(); <<A <<B;
getch();
}
}

// call by Value // function Define // call by Reference USING // define function


#include void swap(int X, int C++ referencing void swap(int&X,
<iostream.h> Y) #include <iostream.h> int&Y)
#include<conio.h> { #include<conio.h> {
void main () int T; void main () int T;
{ T=X { T=X
void swap(int ,int) X= Y; void swap(int& , int&) X= Y;
int A, B; Y = T; int A, B; Y = T;
cout<<”Enter the value of A } cout<<”Enter the value of A }
and B”; and B”;
cin>> A >> B; cin>> A >> B;

cout<<”Before swap the cout<<”Before swap the content


content of A and B are “ of A and B are “ <<A <<B;
<<A <<B;
swap(A , B);
swap(A , B);
cout<<”After swap the content
cout<<”After swap the of A and B are “ <<A <<B;
content of A and B are “ getch();
<<A <<B;
getch(); }

P a g e | 42
Computer Science ( D9) : XII - Paper –I

POINTERS AND ARRAYS


The concept of array is very much similar to the one of pointer. In fact, the identifier of an
array is equivalent to the address of its first element, as a pointer is equivalent to the address
of the first element that it points to, so in fact they are the same concept. For example,
supposing these two declarations:
int numbers [20];
int * p;

The following assignment operation would be valid:

p = numbers; //p = &number[0];

After that, p and numbers would be equivalent and would have the same properties.

// array and pointer p = ary; // p = &ary[0];


#include<iostream.h>
#include<conio.h> cout<<"the content of array using pointer..."<<endl;
void main() for(i =0 ; i< 5 ; i++,p++)
{ {
clrscr(); cout<<*p<<endl;
int *p, ary[5],sum=0; sum = sum + *p;
cout<<"Enter the value of array::"; }
for(int i =0 ; i< 5 ; i++) cout<<”The sum of all the contents of the array is
cin>>ary[i]; :”<<sum;
getch();
}

OBJECT ORIENTED PROGRAMMING


Definition of OOP:
“Objects Oriented Programming is an approach that provides a way to modularizing
programs by creating partitioned memory area (objects) for both data and functions that can
be used as templates for creating copies of such modules on demand.”
Q: Differentiate between traditional procedural programming approach and object
oriented programming approach. Or what is object oriented programming? Enlist the
features of object oriented programming.
*Some characteristic of Procedure Oriented Programmingare:
1) Emphasis is on doing things (algorithms)
2) Large programs are divided into smaller programs known as functions.
3) Data move openly around the system from function to function.
4) Functions transform data from one form to another.
5) Employ top-down approach in program design.
* Some of the major features of Objects Oriented Programming are:
1) Emphasis on data rather than procedure.
2) Program are divided into entities are known as objects.
3) Data is hidden and cannot be accessed by external functions.
4) Objects may communicate with each other through functions.
5) Follows bottom-up approach in program design.

P a g e | 43
Computer Science ( D9) : XII - Paper –I

Discuss the following terms of OOPs:


Q. Explain the following concepts related toobject oriented programming
1) Objects: objects are the basic run-time entities in an object oriented system. They
may represent a person, a bank account, a table of data or any item that the program
must handle.
2) Classes: The entire set of data and code of an object can be a user defined data type
with the help of a class. In fact objects are variables of type class.
3) Data Abstraction: In oops, the collection of data and functions(methods).
4) Data Encapsulation: The wrapping up of data and functions into a single unit (called
Class) is known as encapsulation.
5) Data hiding: The data is not accessible to the outside world and only those functions
which are wrapped in the class can access only. This insulation of the data from direct
access by the program is called data hiding.
6) Inheritance: process by which creating a new class called derived class from old one
called base class without modifying the program.
7) Polymorphism: (Poly:-> many; morphism:-> form) means the ability to take more
than one form e.g. Operator overloading, functions overloading, virtual function etc.
8) Dynamic Binding: Binding refers to the linking of a procedure call to the code to be
executed in response to the call. There are two type of binding i) Compile time
binding and ii) run time binding.

Q. Explain the structure of a general C++ program (Object Oriented Programming)

PROGRAMMING STRUCTURE OF OOP:

Include files

Class declaration

Class functions definitions

Main function program

Q. What is a Class? Explain the general form of class declaration.

DECLARATION OF CLASS:
A class is way to bind the data and its associated functions together. It allows the data (and
functions) to be hidden.
Classes are generally declared using the keyword class, with the following format:
classclass_name
{
private:
Variables declarations; // data members
Functions declarations; // member functions
public:
Variables declarations;//data members
Functions declarations;//member functions
};

P a g e | 44
Computer Science ( D9) : XII - Paper –I

wherethe class_name is identifiers for the class. The body of the declaration can contain
members that can be either data or function declaration, and optionally access specifiers.
Access specifiers is one of the following three keywords: private, public or
protected. These specifiers modify the access rights that the members following them
acquire:

 private members of a class are accessible only from within


other members of the same class or from their friends. The data
hiding (using private) is the key features.
 protectedmembers are accessible from members of their
same class and from their friends, but also from members of
their derived classes.
 publicmembers are accessible from outside the class.

By default, all members of a class declared with the


class keyword have private access for all its members. Therefore, any member that is
declared before one other class specifier automatically has private access. For example:

classcircle
{
float r, area; //data member
public:
voidgetrad(flaot); // member function
void calarea(); //member functions
intdisplayarea (void); //member function
};

Declares a class (i.e., a type) called circle. This class contains four members: two data
members of type float (data member r and data member area) with private access
(because private is the default access level) and two member functions with public access:
getrad(float), calarea() and displayarea(), of which for now we have only included
their declaration, not their definition.

The variable 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 data member and member function) can be accessed
from the outside the class.

Q. Describe how member function of class can be defined outside the class definition
and inside the class definition.

DEFINING MEMBER FUNCTIONS:


Member functions can be defined in two places:
 Outside the class definition
 Inside the class definition

P a g e | 45
Computer Science ( D9) : XII - Paper –I

Outside the Class definition:


member functions that are declared inside a class have to be defined separately outside the
class. The general form of a member function definition is:

Return_typeclass_name :: function_name(arguments declaration)


{
Function body
}
The member label class_name:: tells the compiler that the function function_name belongs
to the class class_name. The symbol:: is called as the scope resolution operator. We can
defined a member function outside the class definition make it inline using the qualifiers
inline in the header line of functions definition.
void circle :: getrad() void circle :: calarea()
{ {
cout<< “Enter the value of radius :”; area = 3.14* r *r;
cin>> r; }
}

inlinevoid circle :: getrad()


{
cout<< “The area of circle is :”<<area;
}
Inside the class definition:
 Another method of defining function is to replace the function declaration by the actual
function definition inside the class. When a function is defined inside the class, it as an
Inline functions (by default). For example:
class circle
{
private:
float r, area;
public:
voidgetrad()
{
cout<<”Enter the value of radius:”;
cin>>r;
}
};

Q. What is an object? Describe how members of a class be accessed using object of that
class?
CREATING OBJECTS:
Once a class has been declared, we can create variables of that type by using the class name
(like any other build-in type variable). This statement should be define inside the main
program (function) i.e. void main()

Syntax: class class_name var1, var2, …..;

P a g e | 46
Computer Science ( D9) : XII - Paper –I

Where keyword class is optional, followed name of the class declared, and var1, var2 are the
variables declared of type class class_name called as objects
E.g.class circle X;
class circle X1,X2;
circleZ; // where X,X1,X2, Z are the objects of the type class circle

The declaration of an object is similar to that of a variable of any basic type ieint X; int
X1,X2 etc.

ACCESSING CLASS MEMBER:


The private data of a class can be accessed only through the member functions of that class.
The main() cannot contain statements that access r and area directly. The following is the
format for calling a member function:
.
object_name function_name(argument declared);

Dot operator (.)

e.g.X.getrad();
X.getrad(2.0);
X.r = 2.0 ; // invalid accessed through object directly, can be accessed only through a member function.

// To find the area of circle using OOP //member function are define outside the class
#include<iostream.h> void circle::calarea()
#include<conio.h> {
class circle area = 3.14 * r * r;
{ }
private:
void circle::displayarea()
float r, area; // data members
{
public: cout<<"The area of the circle is ::"<<area;
void getrad() }
{
cout<<"Enter the value of radius :"; //main program
cin>>r; void main()
} {
clrscr();
void calarea(); // member function class circle X; // create object X of type
void displayarea(); //member function X.getrad(); //access members through object X
}; X.calarea();
X.displayarea();
getch();
}

//To find the area of circle using OOP with parameter as void circle::displayarea()
variable. {
#include<iostream.h> cout<<"The area of the circle is ::"<<area;
#include<conio.h> }

P a g e | 47
Computer Science ( D9) : XII - Paper –I

class circle
{ //main program
private: void main()
float r, area; // data members {
public: clrscr();
void getrad(float R) class circle X; // create object X of type class circle
{ float R;
r = R; cout<<"Enter the value of radius :";
} cin>>R;
void calarea(); // member function X.getrad(R); // access member function with parameter
through object X
void displayarea(); //member function X.calarea();
}; X.displayarea();
//member function are define outside the class getch();
void circle::calarea() }
{
area = 3.14 * r * r;
}

MEMORY ALLOCATION FOR OBJECTS: The member functions are created and place
in the memory space only once. Since all the objects belonging to that class use the same
member functions. Only space for member variables is allocated separately for each object.

Q. Explain the short the three special characteristics of a statics data member in a class?

STATIC DATA MEMBER:


A data member of a class can be qualified as static. The properties of a static member
variable are similar to that of a C static variable. A Static member variable has certain special
characteristics:
1) It is initialized to zero when the first object of its class is created. No other
initialization is permitted.
2) Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
3) It is visible only within the class, but its lifetime is the entire program.
Static variables are normally used to maintain values common to the entire class. For
example, a static data member can be used as a counter that records the occurrences of
all the objects.

P a g e | 48
Computer Science ( D9) : XII - Paper –I

int item :: count // definition of static data member

Program: void main()


#include<iostream.h> {
Class item Item A, B, C;
{ A.getcount();
private: B.getcount();
static int count; // count is static C.getcount();
int number; A.getdata(100);
public: B.getdata(200);
void getdata(int a) C.getdata(300);
{ cout<<”After reading data”<<endl;
number = a; A.getcount();
count ++; B.getcount();
} C.getcount();
void getcount() getch();
{ }
cout<<”COUNT :”<<count<<endl; The output would be:
} COUNT :0
}; COUNT :0
COUNT :0
int item :: count; // count defined
After reading data
COUNT :3
COUNT :3
COUNT :3

Static Member Function:


Like static member variable, we can also have static member functions. A member function
that is declared static has the following properties:
1) A static function can have access to only other static members (functions or variables)
declared in the same class.
2) A static member function can be called using the class name as follows:
class_name :: function_name;

OBJECTS AS FUNCTION ARGUMENT


Like any other data type an object may be used as a function argument. This can be done in
two ways :
1) A copy of the entire object is passed to the function ( pass-by-value)
2) Only the address of the object is transferred to the function (pass-by-reference)
// program using concept copy of the entire object is void main()
passed to the function. {
#include<iostream.h> clrscr();
#include<conio.h> class time T1,T2,T3; // create objects of type
class time class time
{ T1.gettime(2,45); // access member function through
private:
object
T2.gettime(3,30);
int hours, minute; // data members
public: T3.sum(T1,T2);
void gettime(int h, int m) T1.puttime();
{ T2.puttime();

P a g e | 49
Computer Science ( D9) : XII - Paper –I

hours = h ; cout<<"-----------------------\n";
minute = m; T3.puttime();
} getch();
void puttime() }
{
cout<<hours<< " hours and "; Output:
cout<<minute << " minute \n";
2 hours 45 minute
}
3 hours 30 minute
void sum(time , time); //member
------------------------------
function
6 hours 15 minute
};
//member function are define outside the class
void time ::sum(time t1, time t2)
{
minute = t1.minute + t2.minute;
hours = minute /60;
minute = minute % 60;
hours= hours+t1.hours+t2.hours;
}

Q. What is friend function? Give the characteristics of a friend function. Or Write any
three characteristics of a friend function.

FRIEND FUNCTION:
The private member cannot be accessed from outside the class. That is a non-member
function cannot have an access to the private data of a class because of main concept of the
OOPs are data hiding and encapsulation. Now a friend function can be declared to have
access to these data members. Friend is a special mechanism for letting non-member
functions access private data. A friend function may be either declared or define within the
scope of a class definition. The key word friend informs the compiler that it is not a member
function of the class.
Class ABC
{
------
------
public:
-----
-----
Friend void xyz(); // declared xyz as a friend member function of class ABC
};

A friend function possesses certain special characteristics:


 It is not in the scope of the class to which it has been declared as friend.
 Since it is not in the scope of the class, it cannot be called using the object of that
class. It can be invoked like a normal function without the help of any object.
 Unlike member functions, it cannot access the member names directly and has to use
an object name and dot membership operator with each member name.

P a g e | 50
Computer Science ( D9) : XII - Paper –I

 It can be declared either in the public or the private part of a class without affecting its
meaning.
 Usually, it has the objects as arguments.
#include <iostream.h> void main()
class sample {
{ sample X;
private: X.setvalue();
int a; cout<<”Mean value = “<< mean(X)
int b; <<endl;
public: getch();
void setvalue() }
{
a = 25; Output: Mean value =32.5
b = 40;
}
friend float mean(sample s); //friend
declared
};
float mean(sample s)
{
return float(s.a+s.b)/2.0;
}

Practical problem: void max(xyz m, abc n)


#include<iostream.h> {
class abc; // forward declaration If (m.x>= n.a)
class xyz cout<<m.x;
{ else
private: cout<<n.a;
int x; }
public:
void setvalue(int i) { x = i;} void main()
friend void max(xyz, abc); {
}; xyz T1;
T1.setvalue(10);
class abc abc T2;
{ T2.setvalue(20);
private:
int a; max(xyz,abc);
public:
getch();
void setvalue(int i) { a = i;}
}
friend void max(xyz, abc);
};

P a g e | 51
Computer Science ( D9) : XII - Paper –I

Q. What is a constructor? Why it is called so? Or Give the characteristics of a


constructor/Destructor function. Or what are the syntax rules for writing constructors/
Destructors?

CONSTRUCTOR AND DESTRUCTOR:


A constructor is a special member function for automatic initialization of an object.
Whenever an object is created, the special member function i.e. the constructor will be
executed automatically.

Rules for writing constructor member function:


1) A constructor name must be the same as that of its class name.
2) It is declared with no return type, even don’t uses void word.
3) It may not be inheritance, virtual or static.
4) It should always have public access within the class.
5) Like other C++ functions, they can have default arguments.
6) They invoked automatically when the objects are created.

// program using constructor and void fib::genfib()


destructor {
#include<iostream.h> while(f3<55)
#include<conio.h> {
class fib f3 = f1+f2;
{ cout<<f3<<endl;
private: f1 = f2;
int f1,f2,f3; // \Data Members f2 = f3;
public: }
fib(); // Constructor }
~fib(); // Destructor
{ void main()
cout<<"Object are destroyed....."; {
} clrscr();
inline void genfib();
}; class fib F; // create object and call constructor
when object F is born

//Member functions are define outside F.genfib();


the class
fib::fib() getch();
{ } // destructor will be called here
f1=0;
f2=1;
f3=0;
cout<<f1<<endl<<f2<<endl;
}

P a g e | 52
Computer Science ( D9) : XII - Paper –I

 PARAMETERIZED CONSTRUCTOR: the constructor that can take arguments


are called parameterized constructor.
class integer
{
private:
intm,n;
public:
integer(); // no parameter / arguments
integer (int x , int y =0);// parameterized constructor
-----
------
};

integer :: integer(int x , int y)


{
m = x;
n = y;
}

Call special member function constructor through main() program.

1) Explicitly : integer I1 = integer(10,20);


2) Implicitly : integer(10,20);

 MULTIPLE CONSTRUCTOR IN A CLASS: refer above example


 CONSTRUCTOR WITH DEFAULT ARGUMENTS: refer above example
 COPY CONSTRUCTOR: integer (integer & I1); integer I2(I1); would define the
object I2 at the same time initialize it to the values of I1.

DESTRUCTOR:
A destructor, as the name implies is used to destroy the objects that have been created by
constructor. Like a constructor, the destructor is a member function whose name is same as
the class name but is preceded by tilde (~). Refer previous program.
Rules for writing Destructor function:
1) A destructor name must be the same as that of its class name.
2) It should be preceded by tilde (~).
3) It is declared with no return type, even don’t uses void word.
4) It may not be inheritance, virtual or static.
5) It should always have public access within the class.
6) Like other C++ functions, they can have default arguments.
7) They invoked automatically when the objects are destroyed.

Q. Explain different types of inheritances with suitable examlples.


INHERITANCE (EXTENDING CLASSES)

C++ strongly supports the concept of reusability. This is basically done by creating new
classes, reusing the properties of the existing ones. The mechanism of deriving a new class

P a g e | 53
Computer Science ( D9) : XII - Paper –I

from old one is called inheritance (derivation). The old class is referred to as the Base
class and newly created class is called as Derived class.

The various forms of inheritances are as follows:

A
A B
A

B C D
B C

Single Inheritance Multiple Inheritance Hierarchical Inheritance

A
A

B
B C

C
D

Multilevel Inheritance
Hybrid Inheritance

Above Fig.: Forms of Inheritance


Defining Derived classes: A derived class is defined by specifying its relationship with the
base class in addition to its own details. The general from of defining a derived class is :

Class derived-class-name : visibility-mode base-class-name


{
-------
------- //member of derived class
-------
};

The colon indicates that the derived-class-name is derived from the base-class-name. The
visibility-mode is optional and if present may be either private or public. The default mode
is private.
Example: single inheritance
Class B : public A // public derivation
{
//member of ABC derived and XYZ is base class
};

P a g e | 54
Computer Science ( D9) : XII - Paper –I

Example: Multilevel inheritance


Class B : public A // public derivation
{
//member of ABC derived and XYZ is base class
};

Class C : public B // public derivation


{
//member of ABC derived and XYZ is base class
};
Example: Multiple Inheritances
Class C : public A, public B // public derivation
{
//member of ABC derived and XYZ is base class
};
When the base class is publicly inherited, “public member” of the base class become
“public member” of the derived class and therefore they are accessible to the objects of the
derived class.
When the base class is privately inherited by a derived class, “public member” of the base
class become “private member” of the derived class and therefore public members of the
base can only be accessed by the member function of the derived class.
// single inheritance class result: public student
#include<iostream.h> {
#include<conio.h> private:
class student float tot,per; // data members
{ public:
private: void disdata();
float rollno; // data members };
public: void result :: disdata()
float p,c,m,b,e; {
void getdata(); getdata();
}; tot = p+c+m+b+e;
per =(tot/500)*100;
//member function are define outside the class
cout<<"Total:: "<<tot<<" Percentage
void student :: getdata()
::"<<per;
{
}
cout<<"Enter the mark of 5 subject p c m b
void main()
e ::";
{
cin>>p>>c>>m>>b>>e;
class result z1; // create object
}
z1.disdata(); }
Q. What is operator overloading? Explain with suitable example? Or Write the
advantages of operator overloading.
OPERATOR OVERLOADING AND TYPE CONVERSION:
Operator overloading is one the existing feature of C++ language. C++ has the ability to
provide the operators with a special meaning for a data types. The mechanism of giving such
special meanings to an operator (an additional task to an operator) is known as operator

P a g e | 55
Computer Science ( D9) : XII - Paper –I

overloading. When an operator is overloaded, its original meaning is not lost. Most of
operator of C++ can be overload except the following:
1) Class member access operator (.*, ->*)
2) Scope resolution operator (::)
3) Size operator (sizeof)
4) Conditional operator ( ?:)

Q. What is an operator function? Describe the syntax of an cooperator function.


The general form of an operator function is:
Return-type class-name :: operator op (argument list)
{
Function body…..;
}

Where return-type is the type of value returned by the specified operation an op is the
operator being overloaded. The op is preceded by the keyword operator. operator op is the
function name.

Q. State any eight rules for overloading operator.


RULES FOR OVERLOADING OPERATORS:
 Only existing operators can be overloaded. New operator cannot create.
 The overload operator must have at least one operand that is user defined type.
 It cannot change the basic meaning of an operator.
 There are some operators that cannot be overloaded.
 Unary and binary overloading is allowed.

To process of overloading involves the following steps:


 First create a class that defines the data type that is to be used in the overloading
operation.
 Declared the operator function operator op () in the public section or friend
function.
 Define the operator function can be implement the required operations.
Overloaded operator functions can be invoked by expression such as:
op x or x op or operator op(x)  1) Unary operator overloading and
x op y or x.operator op(y)  2) Binary operator overloading.

//Unary operator overloading void fib::operator ++()


example {
#include<iostream.h> while(f3<55)
#include<conio.h> {
class fib f3 = f1+f2;
{ cout<<f3<<endl;
private: f1 = f2;
int f1,f2,f3; // data members f2 = f3;
public: }
fib(); }
~fib(){ cout<<"Object are
destroyed.....";} void main()
void operator ++();// member function
{

P a g e | 56
Computer Science ( D9) : XII - Paper –I

with no return and no parameter clrscr();


}; class fib F; // create object and call constructor when
//member function are define outside the class object are born
fib::fib() ++F;
{ getch();
f1=0; }
f2=1;
f3=0;
cout<<f1<<endl<<f2<<endl;
}
//Binary Operator overloading sample sample::operator+(sample t)
example {
#include<iostream.h> sample s;
#include<conio.h> s.x = x+t.x;
class sample s.y = y+t.y;
{ return(s) ;
private: }
intx,y; // data members
public: void main()
sample operator+(sample); //operator {
overloading. clrscr();
void getdata(); class sample z1,z2,z3; // create object and call
constructor when object are born
void disdata(); z1.getdata();
}; z2.getdata();

//member function are define outside the class z3 = z1+z2;


void sample :: getdata()
{ z1.disdata();
cout<<"Enter the value of X & Y ::"; z2.disdata();
cin>>x>>y; cout<<"------------"<<endl;
} z3.disdata();
getch();
void sample :: disdata() }
{
cout<<"X= "<<x<<" "<<"Y =
"<<y<<endl;
}

Q. Explain the three types of data conversion in C++ with a suitable example.
TYPE CONVERSIONS:
We know that C++ allows data to the right of an assignment operator is automatically
converted to the type of the variable on the left.
e.g.
int m;
float x = 3.14;
m=x;
convertx to an integer before its value is assign to m. similarly it will happened with in case
of class objects.

P a g e | 57
Computer Science ( D9) : XII - Paper –I

Three types of situations might arise in the data conversion between un-compatible types:
1) Conversion from built-in type to class type.
2) Conversion from class type to build-in type.
3) Conversion from one class type to another type.

Q. What is Polymorphism? Explain the runtime and compile time Polymorphism.

POLYMORPHISM:
Polymorphism is one the major feature of OOPs. It simply means “one name, multiple
form” (poly  many and morphism form)

Polymorphism

Run-time
Compile time
polymorphism
polymorphism

Function Operator Virtual


overloading overloading Functions

Choosing a function and operator in normal way, during compilation time is called as early
binding or static binding or static linkage. This is also known as compile-time polymorphism.
The appropriate member function can be selected at run time called as late binding or
dynamic binding or run-time polymorphism.

Q. State any five basic rules for virtual function that satisfy the compiler requirement.
The general syntax of the virtual function declaration is:
class class-name
{
private:
------------
------------
public:
virtual void getrad();
--------------------
};
Rules for virtual functions:
 The virtual functions must be member of some class.
 They cannot be static members.
 They are accessed by using object pointers.
 A virtual function can be a friend of another class.
 We cannot have virtual constructors.

P a g e | 58
Computer Science ( D9) : XII - Paper –I

FILE HANDLING: DATA FILE OPERATION


Many real-life problems handle large volumes of data and in such situations we need to use
some devices such as floppy disk or hard disk to store the data. The data is stored in these
devices using the concept of files. A file is a collection of related data stored in particular area
on the disk. Programs can be designed to perform the read and write operation on these files.

The input and output system of C++ handles files operations which are very similar to the
console input and output operations. It uses file steam as an interface between the program
and the files. The stream that supplies data to the program is known as input stream and the
one that receives data from the program is known as output stream.

Input stream

read data data input

Program
Disk Files

Output stream

write data data output

File input and output streams


Classes for file stream operations:
The I/O system of C++ contains a set of classes that define the file handling methods. These
include ifstream, ofstream, fstream. These classes are derived from fstreambase and from
the corresponding iostream.h class.
Opening and Closing a File:
1) Opening a files using Constructor
2) Opening a files using member function.
 A constructor is used to initialize an object while it is being created. The class ofstream
is used create the output stream and the class ifstream to create the input stream. For
example, the following statement opens a file named “result” for output.
e.g. ofstreamoutfile(“result”); // open file in output mode
e.g ifstreaminfile(“result”); // open file in input mode
Where ofile is object with argument “result” of type class ofstream.

 The function open() can be open multiple files that use the same stream object.
Syntax :
file-stream-classstream-object;
stream-object.open(“filesname”);
e.g.ofstreamoutfile; // ofile (output) is object of type ofstream
outfile.open(“data.new”); // open() is member function of class ofstream

P a g e | 59
Computer Science ( D9) : XII - Paper –I

e.g.ifstreaminfile; // ifile (input) is object of type ifstream


infile.open(“data.new”); // open() is member function of class ifstream
 Closing a file :
o The member function close() is used to closed file, opened in output or input
mode.
o e.goutfile.close();
o e.ginfile.close();

Example 1: Example 2:
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
#include<fstream.h> #include<fstream.h>
void main() void main()
{ {
clrscr(); clrscr();
ifstreaminfile("data.new"); // constructor
ofstreamoutfile("data.new"); // char ch;
constructor infile.seekg(0,ios::beg); // go to start
char line[100]; while(infile)
cout<<"Enter the your sentence ..."; {
cin.get(line,100,'\n'); infile.get(ch);
outfile<< line; cout<<ch;
}
outfile.close(); infile.close();
getch(); getch();
} }

P a g e | 60

You might also like