Object Oriented Programming Notes
Object Oriented Programming Notes
INTRODUCTION:
A computer cannot understand our language that we use in our day to day conversations,
and likewise, we cannot understand the binary language that the computer uses to do it’s
tasks. It is therefore necessary for us to write instructions in some specially defined
language like C++ which is like natural language and after converting with the help of
compiler the computer can understand it.
C++ COMPILER
A C++ compiler is itself a computer program which only job is to convert the C++
program from our form to a form the computer can read and execute. The original C++
program is called the “source code”, and the resulting compiled code produced by the
compiler is usually called an “object file”.
After compilation stage object files are combined with predefined libraries by a linker,
sometimes called a binder, to produce the final complete file that can be executed by the
computer. A library is a collection of pre-compiled “object code” that provides operations
that are done repeatedly by many computer programs.
Compiling and linking process C++ program Using Turbo C++ Compiler
1
The first and frequently used method for creating program is Turbo C++'s Integrated
Developement Enviornment (IDE). To start IDE type TC at DOS prompt. Or search the
file TC.EXE in your computer and Run it.
Before we begin to learn to write meaningful programs in C++ language, let us have a
look at the various building block of C++ language, also called elements of C++
language....
TOKENS
A token is a group of characters that logically belong together. The programmer can write
a program by using tokens. C++ uses the following types of tokens.
Keywords, Identifiers, Literals, Punctuators, Operators.
1. Keywords
These are some reserved words in C++ which have predefined meaning to compiler
called keywords. Some commonly used Keyword are given below:
2
asm auto break case catch
char class const continue default
delete do double else enum
extern inline int float for
friend goto if long new
operator private protected public register
return short signed sizeof static
struct switch template this Try
typedef union unsigned virtual void
volatile while
2. Identifiers
Symbolic names can be used in C++ for various data items used by a programmer in his
program. A symbolic name is generally known as an identifier. The identifier is a
sequence of characters taken from C++ character set. The rule for the formation of an
identifier are:
3. Literals
Literals (often referred to as constants) are data items that never change their value during
the execution of the program. The following types of literals are available in C++.
* Integer-Constants
* Character-constants
3
* Floating-constants
* Strings-constants
Integer Constants
Integer constants are whole number without any fractional part. C++ allows three types
of integer constants.
Decimal integer constants : It consists of sequence of digits and should not begin with 0
(zero). For example 124, - 179, +108.
Octal integer constants: It consists of sequence of digits starting with 0 (zero). For
example. 014, 012.
A character constant in C++ must contain one or more characters and must be enclosed in
single quotation marks. For example 'A', '9', etc. C++ allows nongraphic characters which
cannot be typed directly from keyboard, e.g., backspace, tab, carriage return etc. These
characters can be represented by using an escape sequence. An escape sequence
represents a single character. The following table gives a listing of common escape
sequences.
Floating constants
4
They are also called real constants. They are numbers having fractional parts. They may
be written in fractional form or exponent form. A real constant in fractional form consists
of signed or unsigned digits including a decimal point between digits. For example 3.0, -
17.0, -0.627 etc.
String Literals
A sequence of character enclosed within double quotes is called a string literal. String
literal is by default (automatically) added with a special character ‘\0' which denotes the
end of the string. Therefore the size of the string is increased by one character. For
example "COMPUTER" will re represented as "COMPUTER\0" in the memory and its
size is 9 characters.
4. Punctuators
5. Operators
5
Operators are special symbols used for specific purposes. C++ provides six types of
operators. Arithmetical operators, Relational operators, Logical operators, Unary
operators, Assignment operators, Conditional operators, Comma operator
C++ supports a large number of data types. The built in or basic data types supported by
C++ are integer, floating point and character. These are summarized in table along with
description and memory requirement
VARIABLES
It is a location in the computer memory which can store data and is given a symbolic
name for easy reference. The variables can be used to hold different values at different
times during the execution of a program.
Declaration of a variable
6
Before a variable is used in a program, we must declare it. This activity enables the
compiler to make available the appropriate type of location in the memory.
float Total;
You can declare more than one variable of same type in a single statement
int x,y;
Initialization of variable
When we declare a variable it's default value is undetermined. We can declare a variable
with some initial value.
int a = 20;
INPUT/OUTPUT (I/O)
C++ supports input/output statements which can be used to feed new data into the
computer or obtain output on an output device such as: VDU, printer etc. The following
C++ stream objects can be used for the input/output purpose.
cout is used in conjuction with << operator, known as insertion or put to operator.
cin is used in conjuction with >> operator, known as extraction or get from operator.
cout << “My first computer"; Once the above statement is carried out by the computer,
the message "My first computer" will appear on the screen.
cin can be used to input a value entered by the user from the keyboard. However, the get
from operator>> is also required to get the typed value from cin and store it in the
memory location.
7
Let us consider the following program segment:
int marks;
cin >> marks; In the above segment, the user has defined a variable marks of integer type
in the first statement and in the second statement he is trying to read a value from the
keyboard.
TYPE CONVERSION
The process in which one pre-defined type of expression is converted into another type is
called conversion. There are two types of conversion in C++.
1. Implicit conversion
2. Explicit conversion
Implicit conversion
Data type can be mixed in the expression. For example
double a;
int b = 5;
float c = 8.5;
a = b * c;
When two operands of different type are encountered in the same expression, the lower
type variable is converted to the higher type variable. The following table shows the
order of data types.
Order of data types
Data type
long double
double
float
long
int
8
char order (highest)
To (lowest)
The int value of b is converted to type float and stored in a temporary variable before
being multiplied by the float variable c. The result is then converted to double so that it
can be assigned to the double variable a.
Explicit conversion
It is also called type casting. It temporarily changes a variable data type from its declared
data type to a new one. It may be noted here that type casting can only be done on the
right hand side the assignment statement.
T_Pay = double (salary) + bonus;
Initially variable salary is defined as float but for the above calculation it is first
converted to double data type and then added to the variable bonus.
CONSTANTS
A number which does not change its value during execution of a program is known as a
constant. Any attempt to change the value of a constant will result in an error message. A
constant in C++ can be of any of the basic data types, const qualifier can be used to
declare constant as shown below:
const float pi = 3.1415; The above declaration means that Pi is a constant of float types
having a value 3.1415.
Examples of valid constant declarations are:
const int rate = 50;
const float pi = 3.1415;
const char ch = 'A';
9
Refer to class notes
A C++ program starts with function called main ( ). The body of the function is enclosed
between curly braces. The program statements are written within the braces. Each
statement must end by a semicolon;(statement terminator). A C++ program may contain
as many functions as required. However, when the program is loaded in the memory, the
control is handed over to function main ( ) and it is the first function to be executed.
// This is my first program is C++
/* this program will illustrate different components of
a simple program in C++ */
# include <iostream.h>
int main ( )
{
cout <<"Hello World!";
return 0;
}
When the above program is compiled, linked and executed, the following output is
displayed on the VDU screen.
Hello World!
First three lines of the above program are comments and are ignored by the compiler.
Comments are included in a program to make it more readable. If a comment is short and
can be accommodated in a single line, then it is started with double slash sequence in the
10
first line of the program. However, if there are multiple lines in a comment, it is enclosed
between the two symbols /* and */
#include <iostream.h>
The line in the above program that start with # symbol are called directives and are
instructions to the compiler. The word include with '#' tells the compiler to include the
file iostream.h into the file of the above program. File iostream.h is a header file needed
for input/ output requirements of the program. Therefore, this file has been included at
the top of the program.
int main ( )
The word main is a function name. The brackets ( ) with main tells that main ( ) is a
function. The word int before main ( ) indicates that integer value is being returned by the
function main (). When program is loaded in the memory, the control is handed over to
function main ( ) and it is the first function to be executed.
Curly bracket and body of the function main ( )
A C++ program starts with function called main(). The body of the function is enclosed
between curly braces. The program statements are written within the brackets. Each
statement must end by a semicolon, without which an error message in generated.
cout<<"Hello World!";
This statement prints our "Hello World!" message on the screen. cout understands that
anything sent to it via the << operator should be printed on the screen.
return 0;
11
This is a new type of statement, called a return statement. When a program finishes
running, it sends a value to the operating system. This particular return statement returns
the value of 0 to the operating system, which means “everything went okay!”.
/* This program illustrates how to declare variable, read data and display data. */
#include <iostream.h>
int main()
{
int rollno; //declare the variable rollno of type int
float marks; //declare the variable marks of type float
cout << "Enter roll number and marks :";
cin >> rollno >> marks; //store data into variable rollno & marks
cout << "Rollno: " << rollno<<"\n";
cout << "Marks: " << marks;
return 0;
}
OPERATORS
Operators are special symbols used for specific purposes. C++ provides six types of
operators.
Arithmetical operators,
Relational operators,
12
Logical operators,
Unary operators,
Assignment operators,
Conditional operators,
Comma operator
Arithmetical operators
Relational operators
The relational operators are used to test the relation between two values. All relational
operators are binary operators and therefore require two operands. A relational expression
returns zero when the relation is false and a non-zero when it is true. The following table
shows the relational operators.
Logical operators
13
The logical operators are used to combine one or more relational expression. The logical
operators are:
Operators Meaning
|| OR
&& AND
! NOT
Unary operators
C++ provides two unary operators for which only one variable is required.
For Example a = - 50;
a = + 50; Here plus sign (+) and minus sign (-) are unary because they are not used
between two variables.
Assignment operator
The assignment operator '=' is used for assigning a variable to a value. This operator takes
the expression on its right-hand-side and places it into the variable on its left-hand-side.
For example: m = 5; The operator takes the expression on the right, 5, and stores it in the
variable on the left, m. x = y = z = 32; This code stores the value 32 in each of the three
variables x, y, and z. in addition to standard assignment operator shown above, C++ also
support compound assignment operators.
14
Increment and Decrement Operators
C++ provides two special operators viz '++' and '--' for incrementing and decrementing
the value of a variable by 1. The increment/decrement operator can be used with any type
of variable but it cannot be used with any constant. Increment and decrement operators
each have two forms, pre and post.
Pre-increment: ++variable
Post-increment: variable++
The syntax of the decrement operator is:
Pre-decrement: ––variable
Post-decrement: variable––
Conditional operator
The conditional operator ?: is called ternary operator as it requires three operands. The
format of the conditional operator is:
Conditional_ expression ? expression1 : expression2;
15
If the value of conditional expression is true then the expression1 is evaluated, otherwise
expression2 is evaluated. int a = 5, b = 6;
big = (a > b) ? a : b; The condition evaluates to false, therefore biggets the value from b
and it becomes 6.
The comma operator gives left to right evaluation of expressions. When the set of
expressions has to be evaluated for a value, only the rightmost expression is considered.
int a=1, b=2, c=3, i; // comma acts as separator, not as an operator
i = (a, b); // stores b into i Would first assign the value of a to i, and then assign value of b
to variable i. So, at the end, variable i would contain the value 2.
As we know that different types of Variables, constant, etc. require different amounts of
memory to store them The sizeof operator can be used to find how many bytes are
required for an object to store in memory. For example
sizeof (char) returns 1
sizeof (int) returns 2
sizeof (float) returns 4
If k is integer variable, the sizeof (k) returns 2.
the sizeof operator determines the amount of memory required for an object at compile
time rather than at run time.
The order in which the Arithmetic operators (+,-,*,/,%) are used in a. given expression is
called the order of precedence. The following table shows the order of precedence.
Order Operators
First
16
Second
Third ()
*, /, %
+, -
Highest
To
Lowest
++ (Pre increment) -- (Pre decrement), sizeof ( ), !(not), -(unary), +(unary)
*,/, %
+, -
<, <=, >, >=
==,!=
&&
?:
=
Comma operator
FLOW OF CONTROL
Statements
17
Statements are the instructions given to the computer to perform any kind of action.
Action may be in the form of data movement, decision making etc. Statements form the
smallest executable unit within a C++ program. Statements are always terminated by
semicolon.
Compound Statement
Null Statement
Writing only a semicolon indicates a null statement. Thus ';' is a null or empty statement.
This is quite useful when the syntax of the language needs to specify a statement but the
logic of the program does not need any statement. This statement is generally used in for
and while looping statements.
Conditional Statements
Sometimes the program needs to be executed depending upon a particular condition. C++
provides the following statements for implementing the selection control structure.
* if statement
* if else statement
* nested if statement
* switch statement
if statement
18
syntax of the if statement
if (condition)
{
statement(s);
}
From the flowchart it is clear that if the if condition is true, statement is executed;
otherwise it is skipped. The statement may either be a single or compound statement.
if-else
if else statement
From the above flowchart it is clear that the given condition is evaluated first. If the
condition is true, statement1 is executed. If the condition is false, statement2 is executed.
It should be kept in mind that statement and statement2 can be single or compound
statement.
19
Nested if statement
The if block may be nested in another if or else block. This is called nesting of if or else
block.
if(condition 1)
statement 1;
else if (condition 2)
statement2;
else
statement3;
if-else-if example
if(percentage>=60)
cout<<"Ist division";
else if(percentage>=50)
cout<<"IInd division";
else if(percentage>=40)
cout<<"IIIrd division";
else
cout<<"Fail" ;
20
switch statement
The if and if-else statements permit two way branching whereas switch statement permits
multiple branching. The syntax of switch statement is:
switch (var / expression)
{
case constant1 : statement 1;
break;
case constant2 : statement2;
break;
.
.
default: statement3;
break;
}
The execution of switch statement begins with the evaluation of expression. If the value
of expression matches with the constant then the statements following this statement
execute sequentially till it executes break. The break statement transfers control to the
end of the switch statement. If the value of expression does not match with any constant,
the statement with default is executed.
FLOW OF CONTROL
Looping statement
21
It is also called a Repetitive control structure. Sometimes we require a set of statements to
be executed a number of times by changing the value of one or more variables each time
to obtain a different result. This type of program execution is called looping. C++
provides the following construct
* while loop
* do-while loop
* for loop
While loop
The flow diagram indicates that a condition is first evaluated. If the condition is true, the
loop body is executed and the condition is re-evaluated. Hence, the loop body is executed
repeatedly as long as the condition remains true. As soon as the condition becomes false,
it comes out of the loop and goes to the statement next to the ‘while’ loop.
22
Note : That the loop body is always executed at least once. One important difference
between the while loop and the do-while loop the relative ordering of the conditional test
and loop body execution. In the while loop, the loop repetition test is performed before
each execution the loop body; the loop body is not executed at all if the initial test fail. In
the do-while loop, the loop termination test is Performed after each execution of the loop
body. hence, the loop body is always executed least once.
for loop
for loop
It is a count controlled loop in the sense that the program knows in advance how many
times the loop is to be executed.
The flow diagram indicates that in for loop three operations take place:
Operation (i) is used to initialize the value. On the other hand, operation (ii) is used to test
whether the condition is true or false. If the condition is true, the program executes the
23
body of the loop and then the value of loop control variable is updated. Again it checks
the condition and so on. If the condition is false, it gets out of the loop.
Jump Statements
* goto statement
* break statement
* continue statement
24
}
The continue statement skips rest of the loop body and starts a new iteration.
LIBRARY FUNCTION
# Include Directive
The # include directive instructs the compiler to read and include another file in the
current file. The compiler compiles the entire code. A header file may be included in one
of two ways.
include <iostream.h>
or
include "iostream.h"
The header file in angle brackets means that file reside in standard include directory. The
header file in double quotes means that file reside in current directory.
LIBRARY FUNCTIONS
Console I/O functions
25
putchar() It takes one argument, which is the character to be sent to output device. It
also returns this character as a result.
gets() It gets a string terminated by a newline character from the standard input stream
stdin.
puts() It takes a string which is to be sent to output device.
FUNCTION
A function is a subprogram that acts on data and often returns a value. A program written
with numerous functions is easier to maintain, update and debug than one very long
program. By programming in a modular (functional) fashion, several programmers can
work independently on separate functions which can be assembled at a later date to create
the entire project. Each function has its own name. When that name is encountered in a
program, the execution of the program branches to the body of that function. When the
function is finished, execution returns to the area of the program code from which it was
called, and the program continues on to the next line of code.
The declaration, called the FUNCTION PROTOTYPE, informs the compiler about the
functions to be used in a program, the argument they take and the type of value they
return.
Define the function.
The function definition tells the compiler what task the function will be performing. The
function prototype and the function definition must be same on the return type, the name,
and the parameters. The only difference between the function prototype and the function
header is a semicolon.
26
The function definition consists of the function header and its body. The header is
EXACTLY like the function prototype, EXCEPT that it contains NO terminating
semicolon.
// function definition
void starline()
{
int count; // declaring a LOCAL variable
for(count = 1; count <=65; count++)
cout<< "*";
cout<<endl;
}
ARGUMENT TO A FUNCTION
Sometimes the calling function supplies some values to the called function. These are
known as parameters. The variables which supply the values to a calling function called
actual parameters. The variable which receive the value from called statement are termed
formal parameters.
27
Consider the following example that evaluates the area of a circle.
#include<iostream.h>
void area(float);
int main()
{
float radius;
cin>>radius;
area(radius);
return 0;
}
void area(float r)
{
cout<< “the area of the circle is”<<3.14*r*r<<”\n”;
}
// Example program
#include <iostream.h>
28
}
//timesTwo function
int timesTwo (int num)
{
int answer; //local variable
answer = 2 * num;
return (answer);
}
CALLING OF FUNCTION
The function can be called using either of the following methods:
i) Call by value
ii) Call by reference
CALL BY VALUE
In call by value method, the called function creates its own copies of original values sent
to it. Any changes, that are made, occur on the function’s copy of values and are not
reflected back to the calling function.
CALL BY REFERENCE
In call be reference method, the called function accesses and works with the original
values using their references. Any changes, that occur, take place on the original values
are reflected back to the calling code.
Consider the following program which will swap the value of two variables.
using call by reference using call by value
#include<iostream.h>
void swap(int &, int &);
int main()
{
29
int a=10,b=20;
swap(a,b);
cout<<a<<" "<<b;
return 0;
}
void swap(int &c, int &d)
{
int t;
t=c;
c=d;
d=t;
} #include<iostream.h>
void swap(int , int );
int main()
{
int a=10,b=20;
swap(a,b);
cout<<a<<" "<< b;
return 0;
}
void swap(int c, int d)
{
int t;
t=c;
c=d;
d=t;
}
output:
20 10
output:
10 20
30
Function With Default Arguments
C++ allows to call a function without specifying all its arguments. In such cases, the
function assigns a default value to a parameter which does not have a mathching
arguments in the function call. Default values are specified when the function is declared.
The complier knows from the prototype how many arguments a function uses for calling.
Example : float result(int marks1, int marks2, int marks3=75); a subsequent function call
average = result(60,70); passes the value 60 to marks1, 70 to marks2 and lets the function
use default value of 75 for marks3.
The function call average = result (60, 70, 80); passes the value 80 to marks3.
INLINE FUNCTION
Functions save memory space because all the calls to the function cause the same code to
be executed. The functions body need not be duplicated in memory. When the complier
sees a function call, it normally jumps to the function. At the end of the function. it
normally jumps back to the statement following the call.
While the sequence of events may save memory space, it takes some extra time. To save
execution time in short functions, inline function is used. Each time there is a function
call, the actual code from the function is inserted instead of a jump to the function. The
inline function is used only for shorter code.
31
* Only shorter code is used in inline function If longer code is made inline then
compiler ignores the request and it will be executed as normal function.
Automatic variable
All variables by default are auto i.e. the declarations int a and auto int a are equivalent.
Auto variables retain their scope till the end of the function in which they are defined. An
automatic variable is not created until the function in which it defined is called. When the
function exits and control is returned to the calling program, the variables are destroyed
and their values are lost. The name automatic is used because the variables are
automatically created when a function is called and automatically destroyed when it
returns.
Register variable
A register declaration is an auto declaration. A register variable has all the characteristics
of an auto variable. The difference is that register variable provides fast access as they are
stored inside CPU registers rather than in memory.
32
Static variable
A static variable has the visibility of a local variable but the lifetime of an external
variable. Thus it is visible only inside the function in which it is defined, but it remains in
existence for the life of the program.
External variable
A large program may be written by a number of persons in different files. A variable
declared global in one file will not be available to a function in another file. Such a
variable, if required by functions in both the files, should be declared global in one file
and at the same time declared external in the second file.
STRUCTURE
A structure is a collection of variable which can be same or different types. You can refer
to a structure as a single variable, and to its parts as members of that variable by using the
dot (.) operator. The power of structures lies in the fact that once defined, the structure
name becomes a user-defined data type and may be used the same way as other built-in
data types, such as int, double, char.
struct STUDENT
{
int rollno, age;
char name[80];
float marks;
};
int main()
{
// declare two variables of the new type
33
STUDENT s1, s3;
//accessing of data members
cin>>s1.rollno>>s1.age>>s1.name>>s1.marks;
cout<<s1.rollno<<s1.age<<s1.name<<s1.marks;
//initialization of structure variable
STUDENT s2 = {100,17,”Aniket”,92};
cout<<s2.rollno<<s2.age<<s2.name<<s2.marks;
//structure variable in assignment statement
s3=s2;
cout<<s3.rollno<<s3.age<<s3.name<<s3.marks;
return 0;
}
Defining a structure
When dealing with the students in a school, many variables of different types are needed.
It may be necessary to keep track of name, age, Rollno, and marks point for example.
struct STUDENT
{
int rollno, age;
char name[80];
float marks;
}; STUDENT is called the structure tag, and is your brand new data type, like int, double
or char.
34
The most efficient method of dealing with structure variables is to define the structure
globally. This tells "the whole world", namely main and any functions in the program,
that a new data type exists. To declare a structure globally, place it BEFORE void
main(). The structure variables can then be defined locally in main, for example…
struct STUDENT
{
int rollno, age;
char name[80];
float marks;
};
int main()
{
// declare two variables of the new type
STUDENT s1, s3;
………
………
return 0;
}
35
structure variable.member name
for example cin>>s1.rollno>>s1.age>>s1.name>>s1.marks;
Initialization of structure variable
Procedural Paradigm
In procedural programming paradigm, the emphasis is on doing things i.e., the procedure
or the algorithm. The data takes the back seat in procedural programming paradigm.
Also, this paradigm does not model real world well.
Class-: A class represents a group of objects that share common properties, behavior and
relationships.
Encapsulation-: The wrapping up of data and associated functions into a single unit is
known as Encapsulation. Encapsulation implements data abstraction.
36
Modularity-: Modularity is the property of a system that has been decomposed into a set
of cohesive and loosely coupled modules.
Base and sub classes-: The class whose properties are inherited is called base class (or
superclass) and the class that inherits the properties is known as derived class(or
subclass).
Derived Class :- The class, which inherits from other classes is called derived class or
Subclass.
Polymorphism-: It is the ability for a message or data to be processed in more than one
form. Polymorphism is a property by which the same message can be sent to objects of
several different classes. Polymorphism is implemented in C++ through virtual functions
and overloading- function overloading and operator overloading.
The outside world is given only the essential and necessary information through public
members, rest of the things remain hidden, which is nothing but abstraction. Abstraction
37
means representation of essential features without including the background details and
explanation.
The mechanism that allows you to combine data and the function in a single unit is called
a class. Once a class is defined, you can declare variables of that type. A class variable is
called object or instance. In other words, a class would be the data type, and an object
would be the variable. Classes are generally declared using the keyword class, with the
following format:
class class_name
{
private:
members1;
protected:
members2;
public:
members3;
};
Where class_name is a valid identifier for the class. The body of the declaration can
contain members, that can be either data or function declarations, The members of a class
are classified into three categories: private, public, and protected. Private, protected, and
public are reserved words and are called member access specifiers. 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. You cannot access it outside of the class.
protected members are accessible from members of their same class and also from
members of their derived classes.
38
Finally, public members are accessible from anywhere where the object is visible.
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.
Once a class is defined, you can declare objects of that type. The syntax for declaring a
object is the same as that for declaring any other variable. The following statements
declare two objects of type student: student st1, st2;
Accessing Class Members
39
Once an object of a class is declared, it can access the public members of the class.
st1.getdata();
Defining Member function of class
You can define Functions inside the class as shown in above example. Member functions
defined inside a class this way are created as inline functions by default. It is also
possible to declare a function within a class but define it elsewhere. Functions defined
outside the class are not normally inline.
When we define a function outside the class we cannot reference them (directly) outside
of the class. In order to reference these, we use the scope re operator, ::
(double colon). In this example, we are defining function getdata outside the class:void
student :: getdata()
{
cout<<"Enter Roll Number : ";
cin>>rollno;
cout<<"Enter Marks : ";
cin>>marks;
}
The following program demostrates the general feature of classes. Member function
initdata() is defined inside the class. Member functions getdata() and showdata() defined
outside the class.
40
rollno=r;
marks=m;
}
void getdata(); //member function to get data from user
void showdata();// member function to show data
};
int main()
{
student st1, st2; //define two objects of class student
st1.initdata(5,78); //call member function to initialize
st1.showdata();
st2.getdata(); //call member function to input data
st2.showdata(); //call member function to display data
return 0;
}
41
CONSTRUCTOR AND DESTRUCTOR
CONSTURCTOR
It is a member function having same name as it’s class and which is used to initialize the
objects of that class type with a legel initial value. Constructor is automatically called
when object is created.
Types of Constructor
student :: student()
{
rollno=0;
marks=0.0;
}
student :: student(int r)
{
rollno=r;
}
Copy Constructor-: A constructor that initializes an object using values of another object
passed to it as parameter, is called copy constructor. It creates the copy of the passed
object.
42
{
rollno = t.rollno;
}
There can be multiple constructors of the same class, provided they have different
signatures.
DESTRUCTOR
A destructor is a member function having sane name as that of its class preceded by
~(tilde) sign and which is used to destroy the objects that have been created by a
constructor. It gets invoked when an object’s scope is over.
~student() { }
Example : In the following program constructors, destructor and other member functions
are defined inside class definitions. Since we are using multiple constructor in class so
this example also illustrates the concept of constructor overloading
#include<iostream.h>
43
}
student(int r, int m) //parameterized constructor
{
rollno=r;
marks=m;
}
student(student &t) //copy constructor
{
rollno=t.rollno;
marks=t.marks;
}
void getdata() //member function to get data from user
{
cout<<"Enter Roll Number : ";
cin>>rollno;
cout<<"Enter Marks : ";
cin>>marks;
}
void showdata() // member function to show data
{
cout<<"\nRoll number: "<<rollno<<"\nMarks: "<<marks;
}
~student() //destructor
{}
};
int main()
{
student st1; //defalut constructor invoked
student st2(5,78); //parmeterized constructor invoked
student st3(st2); //copy constructor invoked
44
st1.showdata(); //display data members of object st1
st2.showdata(); //display data members of object st2
st3.showdata(); //display data members of object st3
return 0;
}
INHERITANCE
Inheritance: It is the capability of one class to inherit properties from another class.
Base Class: It is the class whose properties are inherited by another class. It is also called
Super Class.
Derived Class: It is the class that inherit properties from base class(es).It is also called
Sub Class.
FORMS OF INHERITANCE
Single Inheritance: It is the inheritance hierarchy wherein one derived class inherits from
one base class.
Multiple Inheritance: It is the inheritance hierarchy wherein one derived class inherits
from multiple base class(es)
Hybrid Inheritance:The inheritance hierarchy that reflects any legal combination of other
four types of inheritance.
45
Visibility Mode:It is the keyword that controls the visibility and availability of inherited
base class members in the derived class.It can be either private or protected or public.
Containership: When a class contains objects of other class types as its members, it is
called containership. It is also called containment, composition, aggregation.
Execution of base class constructor
Method of inheritace Order of execution
class B : public A { }; A(); base constructor
B(); derived constructor
class A : public B, public C B();base (first)
C();base (second)
A();derived constructor
46
When both derived and base class contains constructors, the base constructor is executed
first and then the constructor in the derived class is executed. In case of multiple
inheritances, the base classes are constructed in the order in which they appear in the
declaration of the derived class.
Overriding of method(function) in inheritance
We may face a problem in multiple inheritance, when a function with the same name
appears in more than one base class. Compiler shows ambiguous error when derived class
inherited by these classes uses this function.
We can solve this problem, by defining a named instance within the derived class, using
the class re operator with the function as below :
47
BASIC OPERATION ON TEXT FILE IN C++
#include<fstream.h>
int main()
{
ofstream fout;
fout.open("out.txt");
char str[300]="Time is a great teacher but unfortunately it kills all its pupils. Berlioz";
fout<<str;
fout.close();
return 0;
}
#include<fstream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
return 0;
}
#include<fstream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
clrscr();
char ch; int count=0;
48
while(!fin.eof())
{
fin.get(ch);
count++;
}
cout<<"Number of characters in file is "<<count;
fin.close();
getch();
return 0;
}
#include<fstream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
char word[30]; int count=0;
while(!fin.eof())
{
fin>>word;
count++;
}
cout<<"Number of words in file is "<<count;
fin.close();
getch();
return 0;
}
#include<fstream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
char str[80]; int count=0;
while(!fin.eof())
{
fin.getline(str,80);
count++;
}
cout<<"Number of lines in file is "<<count;
49
fin.close();
getch();
return 0;
}
#include<fstream.h>
int main()
{
ifstream fin;
fin.open("out.txt");
ofstream fout;
fout.open("sample.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
fout<<ch;
}
fin.close();
return 0;
}
QUESTIONS SECTION
Question 1
Question 2
Write a program to display the following output using a single cout statement.
Subject Marks
Mathematics 90
Computer 77
Chemistry 69
Question 3
50
Write a program which accept two numbers and print their sum.
Question 4
Question 5
Write a program which accept principle, rate and time from user and print the
simple interest.
Question 6
Write a program which accepts a character and display its ASCII value.
Question 7
Question 8
Question 9
Write a program to check whether the given number is positive or negative (using ?
: ternary operator )
Question 10
Write a program to check whether the given number is even or odd (using ? :
ternary operator )
Question 11
Write a program which accepts days as integer and display total number of years,
months and days in it.
for example : If user input as 856 days the output should be 2 years 4 months 6
days.
51
Question 12
int x = 10;
cout<<x<<x++;
int x = 10;
cout<<++x<<x++<<x;
Question 13
Question 14
Write a program to find the factorial value of any number entered through the
keyboard.
Question 15
i)
**********
**********
**********
**********
ii)
*
**
***
****
*****
iii)
52
*
**
***
****
*****
iv)
1
222
33333
4444444
555555555
Question 16
Question 1
Write a C++ program to find the sum and average of one dimensional integer array.
Question 2
Write a C++ program to swap first and last element of an integer 1-d array.
Question 3
53
Write a C++ program to reverse the element of an integer 1-D array.
Question 4
Write a C++ program to find the largest and smallest element of an array.
Question 5
Question 3
54
{return Percentage;}
};
Write a function in C++, that would read contents of file STUDENT.DAT and
display the details of those Students whose Percentage is above 75.
Question 4
Observe the program segment given below carefully and fill the blanks marked as
Statement 1 and Statement 2 using seekg() and tellg() functions for performing the
required task.
#include <fstream.h>
class Employee
{
int Eno;
char Ename[20];
public:
//Function to count the total number of records
int Countrec();
};
int Item::Countrec()
{
fstream File;
File.open("EMP.DAT",ios::binary|ios::in);
______________________ //Statement 1
int Bytes =______________________ //Statement 2
int Count = Bytes / sizeof(Item);
File.close();
return Count;
}
55