Uploaded by mscsripriya35

notes

advertisement
UNIT – I
Introduction to C++ - key concepts of Object-Oriented Programming –Advantages – Object
Oriented Languages – I/O in C++ - C++ Declarations. Control Structures: - Decision Making
and Statements : If .. else ,jump, goto, break, continue, Switch case statements - Loops in C++ :
for, while, do - functions in C++ - inline functions – Function Overloading.
INTRODUCTION TO C++
C++ is an object oriented programming language & is an extension of C language .
Bjarne Stroustrup at AT & Bell Laboratioreis developed it. He called the language C with
classes. In 1983 the name was changed to C++.
KEY CONCEPTS OF OBJECT ORIENTED PROGRAMMING
1) Data Abstraction
Abstraction directs to the procedure of representing essential features without
including the background details.
2) Encapsulation
The packing of data and functions in to a single component is known as
encapsulation.
3) Inheritance
It is the method by which objects of one class get the properties of objects of
another class.
4) Polymorphism
It allows the same function to act differently in different classes.
5) Dynamic Binding
Binding means connecting one program to another program that is to be
executed in reply to the call. It is also known as late binding.
6) Reusability
Object oriented technology allows reusability of the classes by executing them
to other classes using inheritance.
7) Delegation
When an object of one class is used as a data member in another class such
composition of object is known as delegation.
8) Genericity
This feature allows declaration of variables without specifying exact data type.
The compiler identifies the data type at run time.
ADVANTAGES
 OOPS can be comfortably upgraded.
 Using inheritance redundant program, codes can be eliminated & use of previously
defined classes may be continued.
 OOP languages have standard class library.
 All OOP languages can create reusable parts of programs.
OBJECT ORIENTED LANGUAGES
C++
Smalltalk
Java
INPUT & OUTPUT(I/O) IN C++
Input Stream
 It does read operation through keyboard.
 It uses cin as object.
 The cin statement is used to read data through the input device & uses the extraction
operator “ >> “.
Syntax:
Example
cin>> varname;
int a;
float b;
cin>>a>>b;
Output stream
 It display contents of variables on the screen.
 It uses insertion operation “ << ” before variable name.
Syntax :
Example
cout << variable;
int a;
float b;
cout <<a << b;
Typecasting
It refers to the conversion of data from one basic type to another by applying external
use of data type keywords.
# include<iostream.h>
#include<conio.h>
void main()
{
int i;
for(i=65;i<=91;i++)
cout<<(char)i;
}
cin - Standard input, usually keyboards, corresponding to stdin in C.
It handles input from input devices.
cout - Standard output, usually screen, corresponding to stdout in C.
It passes data to output devices such as monitor and printer.
clog - It control error messages that are passed from buffer to the standard error device






cerr - Standard error output, usually screen, corresponding to stderr in C. It controls
the unbuffered output data. It catches the error & passes to standard error device
monitor.
get() – It is used to read a single character from the keyboard.
put() – It is used to display a single character on the screen. Examples
cin.get(ch);
cin.put(ch);
getline() – It is used to read the string including whitespace. The object cin calls the
function. Syntax:
cin.getline(variable,size);
Example: cin.getline(name,30);
read() – It is used to read text through the keyboard. Syntax
cin.read(variable,size);
write() – it is used to display the string on screen. Syntax
cout.write(variable,size);
C++ DECLARATION
Parts of C++ program
The parts are shown below
Include files
Class declaration
Class function definition
main() function
1. Include files - It controls the header files for function declaration. Each header file
has an extension.
e.g # include “ iostream.h”
2. Class declaration - A class is defined in this section. It contains data variable, data
member, function prototype, function definition.
3. Class function definition – This block contains definition of function.
4. main() - C++ programs always starts it execution from main().
b) Tokens
The smallest individual unit in a program is called as token. Following are the tokens
available in C++ Programming.
C++ Tokens
Keywords
Identifiers
Constants
Special
characters
Operators
1.
2.
3.
4.
5.
Keywords:
Predefined word in program. Eg: float, while, class
Identifiers:
Refers to the name of variables, functions, arrays. Eg: a, b[], add()
Constants:
Fixed values that do not change.
Special characters: Eg:#,{,}
Operators:
Used to do some operation. Eg:+,*,&&
Data types in C++
1. Basic data types
2. Derived data types
3. User defined data type
4. Void data type
1. Basic data types
2. Derived data type
a) Pointer
A pointer is a memory variable that stores a memory address. Pointer can have
any name i.e legal for other variable and is declared in the same fashion like other
variable but it is always denoted by ‘*’ operator. Example
int *a;
float *f;
b) Function
A function is a self-contained block or subprogram of one or more statement
that perform a specific task when called. Example
main( )
{
fun A( );
fun B( );
}
c) Array
Array is a collection of elements of homogenous data type.
Program
# include<iostream.h>
#include<conio.h>
void main()
{
int a[5], *p;
int i;
clrscr();
cout<<”enter the array element ”;
for(i=0;i<5;i++)
cin>>a[i];
p=a;
cout<<”elements are”;
for(i=0;i<5;i++)
cout<<*(p+i);
getch();
}
d) Reference
It is used to define a reference variable. This variable prepares an alias for a
previously defined variable.
Syntax :
data type & reference variable name=variable name;
Example
int qty=10;
int &qt=qty;
3. User defined data type
a) Structure & classes:
Structure
struct student
{
char nm[30];
char sex[10];
int roll;
}
Classes
class student
{
char nm[30];
char sex[10];
int roll;
void input(void);
};
b) Union
union number
{
char c;
int i;
}
union number num;
c) Enumerated data type
Keyword: enum
enum logical {true,false}
Void data type
It is also known as empty data type. Example
void display()
{
cout<<”Hello”;
}
Operators in C++
1) Insertion operator (<<)
2) Extraction operator (>>)
3) Scope access /resolution operator (::)
4) New (Memory allocation operator)
5) Delete (Memory release operator)
6) Comma operator (,)
7) Reference operator (&)
8) Dereferencing operator (*)
DECISION MAKING AND BRANCHING or
CONDITIONAL STATEMENTS
C++ language supports the following statements known as control or decision making
statements.
1. if statement
2. switch statement
IF STATEMENT
The if statement may be implemented in different forms depending on the complexity
of conditions to be tested.
1. Simple if statement
2. if…..else statement
3. Nested if…..else statement
4. elseif ladder
SIMPLE IF STATEMENT
The general form of simple if statement is given below. The ‘statement-block’ may be
a single statement or a group of statements. If the test expression is true, the statement-block
will be executed; otherwise the statement-block will be skipped and the execution will jump
to the statement-x.
if(test expression)
{
statement-block;
}
statement-x;
Entry
Test
Exprn?
True
Statement-block
False
Statement-x
E.g.
if( amt > 0)
Next Statement
{
cout<<“account balance is”<<amt;
}
cout<<“No balance in account”;
THE IF…ELSE STATEMENT
The if….else statement is an extension of simple if statement. The general form is
if(test expression)
{
true-block statements;
}
else
{
false-block statements;
}
statement-x;
If the test expression is true, then the true block statements are executed; otherwise
the false block statement will be executed.
Entry
Test
Exprn?
False- Statement
True- Statement
Statement-x
Eg:
if( a > b)
{
cout<<“A is big number”;
}
else
{
cout<<“B is big number”;
}
NESTING OF IF…..ELSE STATEMENTS
When a series of decisions are involved, we may have to use more than one if….else
statements, in nested form as follows.
if(test condition 1)
{
if(test condition 2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
Eg.
if( age > 18)
{
if(s == 1)
cout<<“ Male Voter”;
else
cout<<“Female Voter”;
}
else
{
cout<<“Not eligible to vote”;
}
THE ELSEIF LADDER
The general form of elseif ladder is
if(condition 1)
statement-1;
else if (condition 2)
statement-2;
else if (condition 3)
statement-3;
……….
……….
else if (condition n)
statement-n;
else
default statement;
statement – x;
E.g.
if(unit <= 200)
charge = 1 * unit;
else if(unit <= 400)
charge = 2 * unit;
else if (unit <= 600)
charge = 3 * unit;
else
charge = 5 * unit;
THE SWITCH STATEMENT
Switch statement is used for complex programs when the number of alternatives
increases. The switch statement tests the value of the given variable against the list of case
values and when a match is found, a block of statements associated with that case is executed.
The general form of switch statement is
switch(expression)
{
case 1:
block-1
break;
case 2:
block-2
break;
…….
…….
default:
default-block
break;
}
statement-x;
Eg:
switch(a)
{
case 1:
cout<<“Rose”;
break;
case 2:
cout<<“Lotus”;
break;
case 3:
cout<<“Lilly”;
break;
default:
cout<<“No flower”;
break;
}
Switch
Expression
Value=1
block 1
Value = 2
block 2
….
….
….
default block
statement-x
THE GOTO STATEMENT
C supports the goto statement to branch unconditionally from one point of the
program to another. The goto requires a label in order to identify the place where the branch
is to be made. A label is a valid variable name and must be followed by a colon. The general
from is
goto label
----------label:
statement;
label:
statement;
----------goto label
Note: A label can be anywhere in the program, either before or after the goto statement
Eg:
void main()
{
int a, b, c ;
read:
cin>>a;
if(a == 0) goto read;
cin>>b;
if(b == 0) goto read;
c = a*b;
cout<< c;
}
JUMPS IN LOOPS
C permits a jump from one statement to another within a loop as well as the jump out
of a loop.
Jumping out of a Loop
An early exit from a loop can be accomplished by using the break statement or the
goto statement. When the break statement is encountered inside a loop, the loop is
immediately exited and the program continues with the statement immediately following the
loop. When the loops are nested, the break would only exit from the loop containing it. That
is, the break will exit only a single loop.
for(initialization; test condition; increment)
{
--------if(---------)
break;
--------}
Statement-x;
Skipping a part of a Loop
Like the break statement, C supports another similar statement called the continue
statement. break causes the loop to be terminated whereas continue causes the loop to be
continued with the next iteration after skipping any statements in between.
The continue statement tells the compiler, “SKIP THE FOLLOWING
STATEMENTS AND CONTINUE WITH THE NEXT ITERATION”. The format of the
continue statement is simply
continue;
The use of continue statement in loops.
(a)
while(test-condition)
{
--------if(--------)
continue;
------------------}
(c)
(b)
do
{
--------if(---------)
continue;
----------------}while(test-condition);
for(initialization; test condition; increment)
{
--------if(---------)
continue;
--------}
DECISION MAKING AND LOOPING
Looping is a sequence of statements executed until some conditions for termination is
satisfied. The C++ language provides for three loop constructs for performing loop
operations. They are
1. The for loop
2. The while loop
3. The do..while loop
The for Loop
The for loop is entry-controlled loop. The general form of the for loop is
for(initialization ; test-condition ; increment)
{
body of the loop;
}
Initialization of the control variables is done first. The value of the control variable is
tested using the test-condition. If the condition is true, the body of the loop is executed;
otherwise the loop is terminated. Example
for(i = 0; i < 10; i++)
{
cout<<i;
}
The While Loop
The basic format of the while statement is
initialization;
while(test condition)
{
body of the loop;
}
The while is an entry–controlled loop statement. The test-condition is evaluated and if
the condition is true, then the body of the loop is executed. Example
i=0;
while(i < 10)
{
cout<<i;
i++;
}
The do…while Loop
Since the test-condition is evaluated at the bottom of the loop, the do…..while loop
provides an exit-controlled loop and therefore the body of the loop is always executed at least
once. The Syntax is
initialization;
do
{
body of the loop;
}
while(test condition);
Example
i=0;
do
{
cout<<i;
i++;
} while(i < 10);
FUNCTIONS IN C++
DEFINITION OF FUNCTIONS
A function definition or function implementation has the following 6 elements
grouped as function header and function body
1. Function name
2.
3.
4.
5.
6.
Function type
List of parameters
Local variable declarations
Function statement
Return statement
function header
function body
The general format of a function definition is
function_type function_name(parameter list)
{
local variable declarations;
statement-1;
statement-2;
………
………
return statement;
}
Function
The
consists of 3 parts
a. Function type or return type
b. Function name
c. Parameter list
Header
function header
Name and Type
The function name is a valid identifier. Hence the same rules for forming a C variable
must be used. The function type specifies the type of value (int or float) that the function will
return. If no return type is given then by default integer type is taken. If the function doesn’t
return anything then return type void is used. Example
int sum( ) {…}
float mul( ){…..}
void printing( ) {….}
- don’t return a value
Formal Parameter List
The parameter list declared the variables that will send and receive the data sent by
the calling program. The parameter list is also known as arguments. Example
int sum(int a, int b){……}
float mul(float x, float y){…..}
Function Body
The function body contains the declaration and statement necessary for perform the
required work. It has
a. Local declaration of variables
b. Function statements
c. Return statement
Local variables defined inside the functions have scope only inside the function.
When function reaches return statement, the control is transferred back to calling program.
For eg:
int add( int a, int b)
{
int c;
- local variable
c=a+b;
- statement for addition
return(c);
- returns the result
}
RETURN VALUES AND THEIR TYPES
It is possible to pass any number of values to the called function but the called
function can return only one value. The return statement can take the form:
return
or
return(expression);
Example,
int add( int a, int b)
{
int c;
c=a+b;
return(c);
}
FUNCTION CALLS
Eg:
A function can be called by simply using the function name in the statement.
main()
{
int p;
p = mul(10,5);
printf(“%d ”, p);
}
int mul( int a, int b)
{
int c;
c=a*b;
return(c);
}
When the compiler executes the function call, the control is transferred to the function
mul(x,y). Here value 10 is assigned to variable a and value 5 is assigned to value b. The
statement c=a*b is executed where c gets the value 50 and finally the value is returned to
variable p and gets printed.
FUNCTION DECLARATION
All functions must be declared before they are called. A function declaration has the
following parts
1. Function type
2. Function name
3. Parameter list
4. Terminating semicolon
The general format is
function_type function_name (parameter list);
Example
int mul( int a, int b);
- function prototype
The parameter list must be separated by commas. If parameter list is empty then it
should be written as void. The return type is optional. The declarations are placed above all
the function then it is called as global prototype. When it is placed inside a function then it is
called as local prototype.
Passing Arguments
The main objective of passing arguments to function is message passing. It is also
known as communication between two function i.e caller & callee function.
Call by value (Pass by value)
Value of actual argument is passed to the formal argument & operation is done on the
formal argument. Any change in formal argument does not affect the actual argument
because formal arguments are photocopy of actual arguments.
#include< iostream.h>
void main()
{
int x,y;
void swap(int,int);
cout<<”enter value of x and y”;
cin>>x>>y;
swap(x,y);
}
void swap(int a, int b)
{
int k;
k=a; a=b; b=k;
cout<<”a=”<<a<<”b=”<<b;
}
Call by Address (Pass by address)
Instead of passing value address are passed. Function operates on addresses rather
than values. The formal arguments are pointers to the actual argument hence, changes made
in the arguments are permanents.
#include<iostream.h>
void main()
{
int x,y;
void swap(int * ,int *);
cout<<”enter value of x and y”;
cin>>x>>y;
swap(&x, &y);
cout<<”x=”<<x<<”y=”<<y;
}
void swap(int *p, int *q)
{
int k;
k=*p; *p=*q; *q=k;
}
Call by reference (Pass by reference)
Following is an example for pass by reference
#include<iostream.h>
void main()
{
int x,y;
void swap(int & , int &);
cout<<”enter value of x and y”;
cin>>x>>y;
swap(x, y);
cout<<”x=”<<x<<”y=”<<y;
}
void swap(int &p, int &q)
{
int k;
k=p;
p=q;
q=k;
}
Default Arguments
C++ compiler allows the programmer to assign default values in function prototype.
When the function is called with less parameter or without parameter the default values are
used for operation.
#include <iostream.h>
void main()
{
int sum(int a,int b=10;int c=15,int d=20);
int a=2;int b=3; int c=4; int d=5;
cout<<sum(a,b,c,d);
cout<<sum(a,b,c);
cout<<sum(a,b);
cout<<sum(a);
cout<<cum(b,c,d);
}
int sum(int j, int k, int l, int m)
{
return(j+k+l+m);
}
Inline functions
C++ provides a mechanism called inline function. When a function is declared as
inline the compiler copies the code of the function in calling function i.e function body is
inserted in place of function call during compilation. Passing of control between caller and
callee function is avoided.
Syntax
inline function header
{
function body
}
Example program
#include <iostream.h>
inline int square(int j)
{
return(j*j);
}
void main()
{
int p,q;
cout<<”enter a number:” ;
cin>>p;
q=square(p);
cout<<q;
}
Some situation where inline functions may not work are:
1. If a loop, a switch ,or goto exists
2. If function contain static values
3. If fuctions are recursive
4. If a return statement exists.
Function overloading
Defining multiple functions with same name is known as function overloading or
function polymorphism. The overloading function must be different in its argument list &
with different data type.
#include<iostream.h>
int add(int,int);
float add(float,float,float);
int main()
{
clrscr();
float fa,fb,fc,fsum;
int ia,ib,ic,isum;
cout<<”enter integer value:”;
cin>>ia>>ib>>ic;
cout<<”enter float value”;
cin>>fa>>fb>>fc;
isum=add(ia,ib,ic);
cout<<isum;
fsum=add(fa,fb,fc);
cout<<fsum;
return 0;
}
add(int j, int k, int l)
{
return(j+k+l);
}
float add(float a, float b,float c)
{
return(a+b+c);
}
Library function
a) ceil, ceill and floor, floor1
The function ceil, ceill round up given float number. The function floor,floor1 round
down float number. They are defined in math.h header file
#include<iostream.h>
#include<math.h>
void main()
{
float num=3.2;
float d,u;
d=float(num);
u=ceil(num);
cout<<num<<u<<d;
}
b) modf and modf1
The function modf breaks double into integer and fraction elements. The function
modf1 breaks long double into integer and fraction elements.
void main()
{
double f,I;
double num=211.57;
f=modf(num,&i);
cout<<num<<i<<f;
}
c) abs, fabs and labs
The function abs() returns the absolute value of integer. The fabs() returns the
absolute value of a floating point number. The labs() returns the absolute value of a long
number.
Declaration:
int abs(int n);
double fabs(double n);
long int labs(long int n);
d) norm
The function is defined in complex.h header file and it is used to calculate the square
of the absolute value.
#include<iostream.h>
#include<complex.h>
#include<conio.h>
int main(0
{
double x=-12.5;
cout<<norm(x);
return 0;
}
e) complex(), real(), imag() and conj()
complex(): - is defined in complex.h header file & it create complex numbers.
real() :- it returns real part of the complex number .
imag() ;- it returns imaginary part of the complex number.
conj() :- it returns complex conjugate of a complex number.
UNIT II
Classes and Objects: Declaring Objects – Defining Member Functions – Static Member
variables and functions – array of objects –friend functions – Overloading member
functions – Bit fields and classes – Constructor and destructor with static members.
CLASSES & OBJECTS
The classes are the most important feature of C++ that leads to Object Oriented
programming. Class is a user defined data type, which holds its own data members and
member functions, which can be accessed and used by creating instance of that class. The
variables inside class definition are called as data members and the functions are called
member functions.
For example: Class of birds, all birds can fly and they all have wings and beaks. So
here flying is a behavior and wings and beaks are part of their characteristics. And there are
many different birds in this class with different names but they all posses this behavior and
characteristics.
Example
class item
{
private:
int codeno;
float price;
int qty;
public:
void show();
};
void values()
{
cout<<"enter codeno,price,qty";
cin>>codeno>>price>>qty;
}
void show()
{
values();
cout<<codeno<<price<<qty;
}
void main()
{
item a;
a.show();
}
An object can’t directly access the member variables & functions declared in private
section but it can access those declared in public section. The private member of a class can
be accessed by public member function of same class.
Declaring Objects
 Public keyword – it is used to allow an object to access the member variable of a
class directly like structure.
 Private keyword – it is used to prevent direct access to member variable or member
function by the object. By default the class member are private.
 Protected keyword – it is same as private. It is frequently used in inheritance
Defining Member Function
#include<iostream.h>
#include<conio.h>
class item
{
private:
int codeno;
float price;
int qty;
public:
void show()
{
cout<<"enter codeno,price,qty";
cin>>codeno>>price>>qty;
}
};
void main()
{
item ob;
ob.show();
}
Declaring Member Function outside the Class
#include<iostream.h>
#include<conio.h>
class item
{
private:
int codeno;
float price;
int qty;
public:
void show( );
};
void item::show()
{
cout<<"enter codeno,price,qty";
cin>>codeno>>price>>qty;
}
void main()
{
item ob;
ob.show();
}
Static Member Variable
Once a data member variable is declared as static, only one copy of that member is
created for the whole class.
#include<iostream.h>
#include<conio.h>
class number
{
static int c;
int k;
public:
void zero()
{
k=0;
}
void count()
{
++c;
++k;
cout<<c<<k;
}
};
int number::c=0;
void main()
{
number A,B,C;
A.zero;
B.zero;
C.zero;
A.count;
B.count;
C.count;
}
Static Member Function
When a function is defined as static it can access only static member variables &
functions of same class. The non-static member are not available to these function. It can also
declared in private section but it must invoked using a static public function.
#include<iostream.h>
#include<conio.h>
class aa
{
private:
static int c;
public:
static void count()
{
c++;
}
static void display()
{
cout<<c;
}
};
int aa::c=0;
void main()
{
aa::display();
aa::count();
aa::count();
aa::display();
}
Friend Function
C++ allows a mechanism in which a non-member function has access permission to
the private data member of the class. This can be done by declaring a non-member function
as friend to the class whose private data is to be accessed. The function declaration should be
preceded by the keyword friend. The function is defined elsewhere in the program like a
normal C++ function. The function definition does not use either the keyword friend or the
scope operator (::)
A function can be declared as a friend to any number of classes. Special
characteristics are:
 No scope restriction.(Not in the scope of the class)
 It can be called directly without using objects.
 To access data member, it has to use an object name and dot operator with each
member name.
 Usually it has the objects as arguments.
Example program
#include<iostream.h>
#include<conio.h>
class base
{
int a,b;
public:
void get()
{
cout<<"Enter two values:";
cin>>a>>b;
}
friend float mean(base ob);
};
float mean(base ob)
{
return float(ob.a+ob.b)/2;
}
void main()
{
clrscr();
base obj;
obj.get();
cout<<"\n Mean value is : "<<mean(obj);
getch();
}
Output:
Enter two values: 10, 20
Mean Value is: 15
Friend Classes
When all the functions need to access another class in such a situation , we can
declare an entire class as friend class. Friend is not inheritable from one class to another.
Declaring class A to be a friend of class B doesn’t mean that class B is also friend of class A.
therefore, friendship is not exchangeable.
#include<iostream.h>
#include<conio.h>
class B;
class A
{
private:
int a;
public:
void aset()
{
a=30;
}
void show(B);
};
class B
{
private:
int b;
public:
void bset()
{
b=40;
}
friend void A::show(B b);
};
void Ashow(B b)
{
cout<<a<<b.b;
}
void main()
{
clrscr();
A a1;
a1.aset();
B b1;
b1.bset();
a1.show(b1);
getch();
}
Member Function & Non-Member Function
#include<iostream.h>
#include<conio.h>
void moon();
class mem
{
public:
void earth()
{
cout<<"on earth:";
}
};
void main()
{`
clrscr();
moon();
}
void moon()
{
mem j;
j.earth();
cout<<"on moon";
}
Overloading member function
#include<iostream.h>
class A
{
public:
void print (int i)
{
cout << ”Printing int datatype“<< i<< endl;
}
void print (double i)
{
cout << ”Printing double datatype“<< f<< endl;
}
void print (char *c)
{
cout << ”Printing character “<<c<< endl;
}
};
void main()
{
A a;
a.print(5);
a.print(500.123);
a.print(“c++”);
}
BIT FIELDS AND CLASSES
Classes and structures can contain members that occupy less storage than an integral type.
These members are specified as bit fields. The declaration of bit field members follows in the
syntax:
"variable name : number of bits"
 Bit fields provide a mechanism to optimize memory usage by allowing to specify the
exact number of bits required to store data.
 Quite useful in embedded programming like mobile phones where memory is limited.
 Unnamed bit fields with width 0 are used for alignment of the next bit field to the
field type boundary.
Example program:
class MyTime
{
unsigned hour : 5;
unsigned mins : 6;
unsigned secs : 6;
public:
void SetHour(int H)
{
assert ( H < 24 );
hour = H;
}
void SetMins(int M)
{
assert ( M < 60 );
mins = M;
}
void SetSecs(int S)
{
assert ( S < 60 );
secs = S;
}
void Print()
{
cout << hour << ":" << mins << ":" << secs << endl;
}
};
void main()
{
MyTime t;
t.SetHour(12);
t.SetMins(58);
t.SetSecs(23);
t.Print();
cout << "Size of MyTime = " << sizeof(t) << endl;
}
OUTPUT:12:58:23
Size of MyTime = 4
CONSTRUCTOR & DESTRUCTOR
1. C++ provides a pair of inbuilt special member function called constructor &
destructor.
2. The constructor constructs the object allocates memory for data members & also
initializes them.
3. The destructor destroys the object when it is of no use or goes out of scope &
deallocates the memory.
4. The compiler automatically executes these functions.
5. When an object is created, compiler invokes the constructor function.
6. Destructor is executed at the end of the function when objects are of no use & goes
out of scope.
Example
class num
{
private:
int a,b,c;
public:
num();
~num();
};
num:;num()
{
a=0;b=0;c=0;
}
num::~num()
{
cout<<”destructor invoked”;
}
void main()
{
num x;
}
Constructor with Arguments
The constructors are also called parameterized constructor. It is necessary to pass
values to the constructor when an object is created. Example
#include<iostream.h>
#include<conio.h>
class num
{
private:
int a,b,c;
public:
num(int m,int n,int k)
void show()
{
cout<<a<<b<<c;
}
};
num::num(int m,int j,int k)
{
a=m; b=j; c=k;
}
void main()
{
clrscr();
num x=num(4,5,7);
num y(1,2,8);
x.show();
y.show();
}
Constructor Overloading
When a class contains more then one constructor all defined with the same name as
the class but with different number of arguments, is called constructor overloading.
Depending upon number of arguments the compiler executes the appropriate constructor.
Example
#include<iostream.h>
#include<conio.h>
class si
{
private:
float p,i,r;
public:
float SI ;
si(float a,float b,float c);
si(float x,float y);
si(float z);
si();
void out();
};
si::si(float a,float b,float c)
{
p=a;
i=b;
r=c;
}
si::si(float x,float y)
{
p=x;
i=y;
r=5;
}
si::si(float z)
{
p=z;
i=3;
r=2;
}
si::si()
{
p=20;
i=4;
r=2;
}
void si::out()
{
SI=(p*i*r)/100;
cout<<"simple interest:"<<SI<<endl;
}
void main()
{
clrscr();
si a(5.3,2.1,6.3) ;
a.out();
si b(4.5,3.2) ;
b.out();
si c(5.3) ;
c.out();
si d ;
d.out();
getch();
}
Copy Constructor
When we pass the reference of an object to a constructor function, declaration is
known as copy constructor. All copy constructors required one argument with reference to an
object of that class. Using copy constructor, it is possible for the programmer to declare and
initialize ne object using reference of another objects. Example
#include<iostream.h>
#include<conio.h>
class num
{
int n;
public:
num(){ }
num(int k)
{
n=k;
}
num(num &j) //copy constructor
{
n=j.n;
}
void show()
{
cout<<n;
}
};
void main()
{
clrscr();
num J(50);
num K(J);
num L=J; //copy constructor invoked
num M;
M=J;
J.show();
K.show();
L.show();
M.show();
}
Destructor
The destructor is executed when object goes out of scope. It is not possible to define
more than one destructor. The destructor is only way to destroy the object. So, they can’t be
overloaded. Destructor does not require any arguments nor return any values. Example
#include<iostream.h>
#include<conio.h>
int c=0;
class A
{
public:
A();
~A();
};
A::A()
{
c++;
cout<<"\n object created:"<<c;
}
A::~A()
{
c--;
cout<<"\n object destroyed:"<<c;
}
void main()
{
clrscr();
A a1,a2,a3;
getch();
}
Constructor and Destructor with static members
An example is shown below to explain the constructor and destructor with static
members
UNIT III
Operator Overloading: Overloading unary, binary operators – Overloading Friend
functions – type conversion – Inheritance: Types of Inheritance – Single, Multilevel,
Multiple, Hierarchal, Hybrid, Multi path inheritance – Virtual base Classes – Abstract
Classes.
OPERATOR OVERLOADING
The capability to relate the existing operator with a member function and use the
resulting operator with objects of its class as its operands is called operator overloading.
#include<iostream.h>
#include<conio.h>
class number
{
public:
int x,y;
number()
{}
number(int j,int k)
{
x=j;
y=k;
}
number operator +(number D)
{
number T;
T.x=x+D.x;
T.y=y+D.y;
return T;
}
void show()
{
cout<<"x="<<x<<"y="<<y;
}
};
void main()
{
clrscr();
number A(2,3),B(y,5),c;
A.show();
B.show();
C=A+B;
C.show();
getch();
}
Overloading Unary operator
#include<iostream.h>
#include<conio.h>
class number
{
int a,b,c;
public:
number(){}
void getvalue()
{
cout<<"Enter the Two Numbers:";
cin>>a>>b;
}
void operator++()
{
a=++a;
b=++b;
}
void operator--()
{
a=--a;
b=--b;
}
void display()
{
cout<<a<<"+\t"<<b<<"i"<<endl;
}
};
void main()
{
clrscr();
number obj;
obj.getvalue();
obj++;
cout<<"Increment Number\n";
obj.display();
obj--;
cout<<"Decrement Number\n";
obj.display();
getch();
}
Overloading binary operator using friend function
#include<iostream.h>
#include<conio.h>
class num
{
private:
int a,b,c,d;
public:
void in()
{
cout<<"enter a value of a,b,c,d:";
cin>>a>>b>>c>>d;
}
void show();
friend num operator *(int,num);
};
void num::show()
{
cout<<a<<b<<c<<d;
}
num operator *(int a,num t)
{
num tmp;
tmp.a=a*t.a;
tmp.b=a*t.b;
tmp.c=a*t.c;
tmp.d=a*t.d;
return(tmp);
}
void main()
{
clrscr();
num x,z;
x.in();
x.show();
z=3*x;
z.show();
}
Type conversion
Type conversion is a way of changing an entity of one data type into another. An
example would be the conversion of an integer value into a floating point value or its textual
representation as a string, and vice versa.
INHERITANCE
The procedure of creating a new class from one or more existing classes is called
inheritance. The program can defined new member variables and function in the derived
class. The base class remains unchanged. An object of derived class can access members of
base as well as derived class but reverse is not possible. The term reusability means reuse of
properties of base class in the derived class.
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchal Inheritance
5. Hybrid Inheritance
6. Multipath Inheritance
Single Inheritance
It is the inheritance hierarchy wherein one derived class inherits from one base class.
It is the simplest form of Inheritance.
A is the base class. B is the derived class. This type involves one base and one derived class.
Further, no class is derived from Y.
#include<iostream.h>
#include<conio.h>
class A
{
public:
char fname[20];
void getfname()
{
cout<<"Enter Father name :";
cin>>fname;
}
};
class marks : public student
{
public:
char sname[20];
void getsname()
{
cout<<"Enter Son name”;
cin>>sname;
}
void display()
{
cout<<”Father name is”<<fname;
cout<< “Son name is :<<sname;
}
};
void main()
{
A obj;
obj.getfname();
obj.getsname()
obj.display();
}
Multiple Inheritance
In this type of inheritance a single derived class may inherit from two or more than
two base classes.
class A
{
protected:
char fname[20];
public:
void getf()
{
cout<<"Enter father name :";
cin>>fname;
}
};
class mother
{
protected:
char mname[20];
public:
void getm()
{
cout<<"Enter mother nmae :";
cin>>mname;
}
};
class son:public father,public mother
{
public:
void display()
{
cout<<”Father name is :” <<fname;
cout<<” Mother name is :” <<mname;
cout<<”Son name is”<<sname;
}
};
void main()
{
clrscr();
statement obj;
obj.get();
obj.getsm();
obj.display();
getch();
}
Output:
Enter the Roll no: 100
Enter two marks:
90
80
Enter the Sports Mark:
90
Roll No: 100
Total : 260
Average: 86.66
Hierarchical Inheritance
In this type of inheritance, multiple derived classes inherits from a single base class.
class A
{
char fname[20];
public:
void getfname()
{
cout<<"Name: ";
gets(name);
cout<<"Age: ";
cin>>age;
cout<<"Gender: ";
cin>>gender;
}
void display()
{
cout<<"Name: "<<name<<endl;
cout<<"Age: "<<age<<endl;
cout<<"Gender: "<<gender<<endl;
}
};
class student: public person
{
char institute[100], level[20];
public:
void getdata()
{
person::getdata();
cout<<"Name of College/School: ";
gets(institute);
cout<<"Level: ";
cin>>level;
}
void display()
{
person::display();
cout<<"Name of College/School: "<<institute<<endl;
cout<<"Level: "<<level<<endl;
}
};
class employee: public person
{
char company[100];
float salary;
public:
void getdata()
{
person::getdata();
cout<<"Name of Company: ";
gets(company);
cout<<"Salary: Rs.";
cin>>salary;
}
void display()
{
person::display();
cout<<"Name of Company: "<<company<<endl;
cout<<"Salary: Rs."<<salary<<endl;
}
};
int main()
{
student s;
employee e;
cout<<"Student"<<endl;
cout<<"Enter data"<<endl;
s.getdata();
cout<<endl<<"Displaying data"<<endl;
s.display();
cout<<endl<<"Employee"<<endl;
cout<<"Enter data"<<endl;
e.getdata();
cout<<endl<<"Displaying data"<<endl;
e.display();
getch();
return 0;
}
Multilevel Inheritance
It is the inheritance hierarchy wherein subclass acts as a base class for other classes.
class person
{
char name[100],gender[10];
int age;
public:
void getdata()
{
cout<<"Name: ";
gets(name);
cout<<"Age: ";
cin>>age;
cout<<"Gender: ";
cin>>gender;
}
void display()
{
cout<<"Name: "<<name<<endl;
cout<<"Age: "<<age<<endl;
cout<<"Gender: "<<gender<<endl;
}
};
class employee: public person
{
char company[100];
float salary;
public:
void getdata()
{
person::getdata();
cout<<"Name of Company: ";
fflush(stdin);
gets(company);
cout<<"Salary: Rs.";
cin>>salary;
}
void display()
{
person::display();
cout<<"Name of Company: "<<company<<endl;
cout<<"Salary: Rs."<<salary<<endl;
}
};
class programmer: public employee
{
int number;
public:
void getdata()
{
employee::getdata();
cout<<"Number of programming language known: ";
cin>>number;
}
void display()
{
employee::display();
cout<<"Number of programming language known: "<<number;
}
};
void main()
{
programmer p;
cout<<"Enter data"<<endl;
p.getdata();
cout<<endl<<"Displaying data"<<endl;
p.display();
getch();
}
Hybrid Inheritance
The inheritance hierarchy that uses all the combinations of other four types of
inheritance is called as hybrid inheritance.
Example program:
#include<iostream.h>
#include<conio.h>
class stu
{
protected:
int rno;
public:
void get_no(int a)
{
rno=a;
}
void put_no(void)
{
out<<"Roll no"<<rno<<"\n";
}
};
class test:public stu
{
protected:
float part1,part2;
public:
void get_mark(float x,float y)
{
part1=x;
part2=y;
}
void put_marks()
{
cout<<"Marks obtained:"<<"part1="<<part1<<"\n"<<"part2="<<part2<<"\n";
}
};
class sports
{
protected:
float score;
public:
void getscore(float s)
{
score=s;
}
void putscore(void)
{
cout<<"sports:"<<score<<"\n";
}
};
class result: public test, public sports
{
float total;
public:
void display(void);
};
void result::display(void)
{
total=part1+part2+score;
put_no();
put_marks();
putscore();
cout<<"Total Score="<<total<<"\n";
}
int main()
{
clrscr();
result stu;
stu.get_no(123);
stu.get_mark(27.5,33.0);
stu.getscore(6.0);
stu.display();
return 0;
}
Virtual Base Class
The duplication of inherited members due to the multiple paths can be avoided by
making the common base class as virtual base class while declaring the intermediate base
classes. To overcome the ambiguity occurred due to the multipath inheritance.
Example
class student
{
int rno;
public:
void getnumber()
{
cout<<"Enter Roll No:";
cin>>rno;
}
void putnumber()
{
cout<<"\n\n\tRoll No:"<<rno<<"\n";
}
};
class test:virtual public student
{
public:
int part1,part2;
void getmarks()
{
cout<<"Enter Marks\n";
cin>>part1>>part2;
}
void putmarks()
{
cout<<"\tMarks Obtained\n<<part1<<part2";
}
};
class sports:public virtual student
{
public:
int score;
void getscore()
{
cout<<"Enter Sports Score:";
cin>>score;
}
void putscore()
{
cout<<"\n\tSports Score is:"<<score;
}
};
class result:public test,public sports
{
int total;
public:
void display()
{
total=part1+part2+score;
putnumber();
putmarks();
putscore();
cout<<"\n\tTotal Score:"<<total;
}
};
void main()
{
result obj;
clrscr();
obj.getnumber();
obj.getmarks();
obj.getscore();
obj.display();
getch();
}
Download