0% found this document useful (0 votes)
7 views45 pages

C++ New Notes

The document provides an overview of C++, an object-oriented programming language developed by Bjarne Stroustrup, highlighting its features, advantages, and core concepts such as classes, objects, inheritance, polymorphism, and encapsulation. It also discusses input/output operators, manipulators, function overloading, and the structure of C++ programs, including access specifiers and member functions. Additionally, it covers the use of objects as function arguments and arrays of class objects.

Uploaded by

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

C++ New Notes

The document provides an overview of C++, an object-oriented programming language developed by Bjarne Stroustrup, highlighting its features, advantages, and core concepts such as classes, objects, inheritance, polymorphism, and encapsulation. It also discusses input/output operators, manipulators, function overloading, and the structure of C++ programs, including access specifiers and member functions. Additionally, it covers the use of objects as function arguments and arrays of class objects.

Uploaded by

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

Introduction

C++ is an object oriented programming language.


Bjarne stroustrup at AT & T's Bell Lab
C++ is a combination of simula 67 and C.
Program features
Similar to C
Limitations of Procedural language(C-Language)
1. Data given less importance.
2. Data structure. (The way data is organized becomes very critical. since many
functions access the common data.).
3. Relationship to the real world.
It is difficult to design. The problem is that the main components data structure
and function do not model the real world very well.
Here software maintenance will be easier.
Programs become more readable.

OOPS Concept:

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or functions that perform


operations on the data, while object-oriented programming is about creating objects that
contain both data and functions.

Advantages of OOPS:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes the
code easier to maintain, modify and debug

Characteristics of oops

1. Class
2. Objects
3. Data abstraction.
4. Data encapsulation.
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message passing.

Input and output operator


Output operator
cout
Description
The operator << is called as insertion or put to operator. It inserts the contents of
the variable on its right to the object of its left.
Syntax:
cout<<variable 1<<variable 2<<....................<<variable n;
e.g.:
cout<<"C++ is better than C";
cout<<a<<b;
Input operator
cin
Description
The operator >> is called as extraction or get from operator. It extracts the value
from the keyboard and assigns it to the variable on its right.
Syntax:
cin>>variable 1>>variable 2>>.................>>variable n;
e.g.:
cin>>a>>b;
Note
The multiple use of >> and << is called as cascading. The header file to be
included for this operator is <iostream.h>

Manipulators
These are special stream functions that change certain characteristics of
the input and output. These are operators that are used to format the data display.
All the manipulators functions prototypes are defined in the header file
<iomanip.h>
1. endl
This is used to generate a carriage return or line feed character.
e.g.:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
clrscr();
cout<<"Welcome to c++"<<endl;
cout<<"Thank you";
getch();
}
2. setw ()
This is used to set the width of the output field.
Syntax:
setw(int width);
e.g.: man2.cpp

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
int a=10,b=20;
clrscr();
cout<<setw(5)<<a<<setw(5)<<b<<endl;
cout<<setw(10)<<a<<setw(10)<<b;
getch();
}
3. setfill()
This fills the given character in the unused field.
Syntax:
setfill(char)
e.g.: man3.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
int a=2,b=4;
clrscr();
cout<<setfill('*');
cout<<setw(5)<<a<<setw(5)<<b<<endl;
cout<<setfill('$');
cout<<setw(7)<<a<<setw(7)<<b<<endl;
getch();
}
4. setprecision()
It controls the display of the number of digits after the decimal point for the
floating point number.
Syntax:
setprecision(int)
e.g.: man4.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
int a=10,b=3;
clrscr();
float c=(float)a/b;
cout<<setprecision(1)<<c<<endl;
cout<<setprecision(2)<<c<<endl;
cout<<setprecision(3)<<c;
getch();
}
Function overloading

It is the logical method of calling the several functions with the same name.

A function call first matches the prototype having the same no and type of arguments
and then calls the appropriate function for execution. A best match must be unique.

1. Function overloading with different type of parameters


E.g.: funo1.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
int abs(int);
double abs(double);
void main()
{
int a;
double b;
clrscr();
cout<<"Enter the value for a:";
cin>>a;
cout<<"Enter the value for b:";
cin>>b;
cout<<abs(a)<<endl;
cout<<abs(b)<<endl;
getch();
}
int abs(int x)
{
return(x<0?-x:x);
}
double abs(double y)
{
return(y<0.0?-y:y);
}

2. Function overloading with different number of arguments


e.g.: uno2.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
int sum(int,int);
int sum(int,int,int);
void main()
{
int a,b,c;
clrscr();
cout<<"Enter any three nos:";
cin>>a>>b>>c;
cout<<sum(a,b)<<endl;
cout<<sum(a,b,c)<<endl;
getch();
}
int sum(int x,int y)
{
return(x+y);
}
int sum(int p,int q,int r)
{
return(p+q+r);
}

Default arguments
C++ allows as calling a function without specifying all its arguments. In the
function prototype declaration, the default values are given. When a call is made to a
function without specifying an argument, the program will automatically assign values
to the parameters from the default function prototype declaration. Default arguments
facilitate easy development and maintenance of program.
e.g.: funo4.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
int sum(int a,int b,int c=10,int d=20);
void main()
{
int a,b;
clrscr();
cout<<"Enter any two nos:";
cin>>a>>b;
cout<<sum(a,b);
getch();
}
int sum(int a,int b,int c,int d)
{
return(a+b+c+d);
}
Characteristics of OOPS:

1. Class
It is nothing but a user defined data type. It consists of member data and
member functions. Hence a class is a collection of objects of similar type.
The entire set of a data and code of an object can be made a user defined data
type with the help of a class.
2. Objects
Objects contain data and the code to manipulate that data. It is the runtime entity
for a class. We can access the member variable and member functions of a class by
using the objects only.
Objects are called as instance (variables) of a class. Once a class has been
defined we can create any no of objects belonging to that class.
Objects interact by sending messages to one another.
3. Data abstraction
The way of accessing variables of a class or member functions of a class is called
data abstraction. Class uses the concept of data abstraction, and hence they are known
as abstract base class. (ABC)
4. Data encapsulation
The wrapping up of data and functions into a single unit is known as
encapsulation. The data is not accessible to the outside world and only those functions
which are wrapped in the class can access it.
The insulation of the data from direct access by the program is called data
hiding.
5. Inheritance
Inheritance is the process by which objects of one class acquires the properties of
objects of another class.
It provides the idea of reusability. This means that we can add additional
features to an existing class without modifying it.
I.e. we can derive a new class from the existing one. The new class will have the
combined features of both the classes.
6. Polymorphism
Polymorphism is the ability to take more than one form.
It is extensively used in implementing inheritance.
e.g.:
Consider an addition operation. For two no, it will generate a sum.
Similarly if the operands are strings then the operation would produce a third
string by concatenation.
A single object can react on multiple functions.
Overloading
It is same as polymorphism.
We can overload functions, operators etc.
7. Dynamic binding
Binding refers to the linking of a procedure call to the code to be executed in
response to the call.
Dynamic binding means that the code associated with a given procedure call is
not known until the time of the call at runtime.
It is associated with polymorphism and inheritance.
8. Message communication
This is done by using the objects. A message for an object is a request for
execution of a procedure and therefore will invoke a function in the receiving object
that generates the desired result.

Structure of C++ program


It contains four sections.
1. Declaring header files
2. Class declaration.
3. Class functions definitions
4. Main function program

Operators in C++
1. Arithmetic operators
2. Unary operators
3. Relational and logical operators
4. Assignment operator
5. Conditional operator
In addition to this C++ introduces some new operators.
<< - insertion operator
>> - extraction operator
:: - scope resolution operator
::* - pointer to member
declaratory
->* - pointer to member operator
.* - pointer to member operator
new - memory allocation operator
delete - memory release operator
. - member operator

Classes and Objects


Class
A class is a unit which combines both data and the functions that operates on the
data. These functions and dates are collectively called as members. The variables
declared inside the class are known as data members and the variables declared
functions are called as member functions.
Generally a class specification has been two parts.
1. Class declaration
2. Class function definition
The class declaration describes its type and scope of its members.
The class function definitions describe how the class function is implemented.
Class declaration
Syntax:
class user defined name
{
access specifier:
member data;
member function;
};
There are three types of access specifier
1. Private
2. Public
3. Protected

1. Private
The members that have been declared as private can be accessed by the member
function and friend functions of this class. It is not accessible from the outside of the
class.
2. Public
The members that have been declared as public can be accessed by any function
in the outside of the class.
3. Protected
These members can be accessed by the member functions and friend functions
and also by the member functions and friend functions derived form this class. It is not
accessible from the outside functions.
The keyword private, public, and protected is known as visibility labels.
e.g.:
class item
{
private:
int no;
float cost;
public:
void getdata(int a, float b);
void putdata();
};
Defining the object of a class
Once a class has been declared, we can create variables of that type by using the
class name.
In C++, the class variables are known as objects. We may also declare more
than one object in one statement.
Syntax:
class name object name 1, object name 2,.......object name n;
e.g.:
class item x, y, z;
All the member object shares the same copy of the member functions but maintains a
separate copy of the member data.
Accessing class members
The class or member functions of a class are accessed using a dot operator.
Before a dot operator there must be a class object and after a dot operator there
must be a member function.
Syntax:
class object name. member function();
e.g.:
x.getdata ();
y.getdata ();
x.putdata ();
y.putdata ();
The objects cannot access the member data directly. The dates are accessed only by
using the member function.
Objects communicate by sending and receiving messages. This is achieved
through the member functions.

Member functions definitions


Member functions can be defined in two ways.
1. inside the class definitions
2. outside the class definitions.
1. Member function inside the class definition
When a function is defined inside the class it is treated as inline.
e.g.: classa1.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class sample
{
private:
int x,y;
public:
void getdata()
{
cout<<"Enter any two nos:"<<endl;
cin>>x>>y;
}
void putdata()
{
cout<<"Sum="<<sum()<<endl;
cout<<"Diff:"<<diff()<<endl;
cout<<"mul:"<<mul()<<endl;
cout<<"Div:"<<div()<<endl;
}
int sum()
{
return(x+y);
}
int diff()
{
return(x-y);
}
int mul()
{
return(x*y);
}
int div()
{
return(x/y);
}
};
void main()
{
sample o;
clrscr();
o.getdata();
o.putdata();
o.sum();
o.diff();
o.mul();
o.div();
getch();
}

Member function outside the class definition


Member functions can be defined outside the class using scope resolution
operator.
Syntax:
return type class name:: function name()
{
body of the function;
}
e.g.:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class sample
{
private:
int x,y;
public:
void getdata();
void putdata();
int sum();
int diff();
int mul();
int div();
};
void sample::getdata()
{
cout<<"Enter any two nos:"<<endl;
cin>>x>>y;
}
void sample::putdata()
{
cout<<"Sum="<<sum()<<endl;
cout<<"Diff:"<<diff()<<endl;
cout<<"mul:"<<mul()<<endl;
cout<<"Div:"<<div()<<endl;
}
int sample::sum()
{
return(x+y);
}
int sample::diff()
{
return(x-y);
}
int sample::mul()
{
return(x*y);
}
int sample::div()
{
return(x/y);
}
void main()
{
sample o;
clrscr();
o.getdata();
o.putdata();
o.sum();
o.diff();
o.mul();
o.div();
getch();
}

Objects as arguments
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. (Call by value).
2. Only the address of the object is transferred to the function. (Call by reference).
In the first method a copy of the object is passed to the function, any changes
made to the object inside the function do not affect the object used to call the function.
When an address of the object is possessed, the called function works directly on
the actual object used in the call. This means that any changes made to the object inside
the function will reflect in the actual object. This method is efficient since it requires
passing only the address of the object and not the entire object.
e.g.: classa2.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class time
{
int hours,minutes;
public:
void gettime(int h,int m)
{
hours=h;
minutes=m;
}
void puttime()
{
cout<<hours<<"hours and";
cout<<minutes<<"minutes"<<endl;
}
void sum(time t1,time t2)
{
minutes=t1.minutes+t2.minutes;
hours=minutes/60;
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
}
};
void main()
{
time t1,t2,t3;
clrscr();
t1.gettime(2,45);
t2.gettime(3,30);
t3.sum(t1,t2);
t1.puttime();
t2.puttime();
t3.puttime();
getch();
}

Array of class objects


Arrays can be used as member variables in a class.
Syntax:
class user defined name
{
member data’s;
member functions();
};
class user defined name object[max];
Where max is a user defined size of the array of the class object.
e.g.: classa3.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class student
{
private:
int rollno,tm,pm,tot;
char name[20];
public:
void getdetail()
{
cout<<"Enter rollno:";
cin>>rollno;
cout<<"Enter name:";
cin>>name;
cout<<"Enter marks:";
cin>>tm>>pm;
}
void showdetail()
{
tot=tm+pm;
cout<<"Roll no:"<<rollno<<endl;
cout<<"Name:"<<name<<endl;
cout<<"Theory:"<<tm<<endl;
cout<<"Practical:"<<pm<<endl;
cout<<"Total:"<<tot<<endl;
}
};
void main()
{
student obj[10];
int i,n;
clrscr();
cout<<"Enter how many students:";
cin>>n;
for(i=0;i<n;i++)
obj[i].getdetail();
for(i=0;i<n;i++)
obj[i].showdetail();
getch();
}
Static data members
A static member variable has certain special characteristics.
1. It is initialized to zero when the first object of its class it’s 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.
Uses
It is normally used to maintain value common to the entire class.
The type and scope of each static member variable must be defined outside the class
definition. This is necessary because it is stored separately rather than as a part of an
object.
Since they are associated with the class itself rather than with any class object,
they are also known as class variables.
e.g.: classa4.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class item
{
private:
static int count;
int number;
public:
void getdata(int a)
{
number=a;
count++;
}
void getcount()
{
cout<<"Count:";
cout<<count<<endl;
}
};
int item::count;
void main()
{
item a,b,c;
clrscr();
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout<<"After reading data "<<endl;
a.getcount();
b.getcount();
c.getcount();
getch();
}
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 (instead of its objects)
as follows.
class name ::function name();
e.g.: classmf.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class test
{
private:
int code;
static int count;
public:
void setcode()
{
code=++count;
}
void showcode()
{
cout<<"Object no:"<<code<<endl;
}
static void showcount()
{
cout<<"Count:"<<count<<endl;
}
};
int test::count;
void main()
{
test t1,t2;
clrscr();
t1.setcode();
t2.setcode();
test::showcount();
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
getch();
}
Nested classes
A class declared as a member of another class is called as nested class or a class
within another class.
Syntax:
class outer class name
{
private:
member datas of outer class
public:
class inner class name
{
private:
member datas of inner class
public:
member functions of inner class
};
member functions of outer class
};
e.g.: classnes.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class emp
{
private:
int empno;
char name[20];
public:
class emp1
{
private:
float salary;
public:
void getsal()
{
cout<<"Enter salary:";
cin>>salary;
}
void putsal()
{
cout<<"Salary:"<<salary;
}
};
void getdetail()
{
cout<<"Enter emp no:";
cin>>empno;
cout<<"Enter emp name:";
cin>>name;
}
void putdetail()
{
cout<<"Emp No:"<<empno<<endl;
cout<<"Name:"<<name<<endl;
}
};
void main()
{
emp e;
emp::emp1 e1;
clrscr();
e.getdetail();
e1.getsal();
e.putdetail();
e1.putsal();
getch();
}
Friend Function
We know that private data members cannot be accessed from outside the class.
In some situations we need to access private data members. In that case we can use
friend function.
A friend function is a non member function which has full access rights to the
private data members of the class and is declared with the keyword friend.
A friend function possesses certain special characteristics.
1. It is not in the scope of the class to which it has been declared as friend.
2. 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.
3. 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
e.g. A.x
4. It can be declared either in the public or the private part of a class without affecting
its meaning.
5. Usually, it has the objects as arguments.
The friend functions are often used in operator overloading.
Syntax:
friend return type function name( argument list);
e.g.: frifa.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class sample
{
private:
int a,b;
public:
void setvalue()
{
a=25;
b=40;
}
friend float mean(sample s);
};
float mean (sample s)
{
return(float(s.a+s.b)/2.0);
}
void main()
{
sample s;
clrscr();
s.setvalue();
cout<<"Mean value="<<mean(s)<<endl;
getch();
}
Friend Classes
The private members of one class can be accessed from the member functions of
another class by make them as friends.
For e.g. consider two classes first and second. If the class first grants its
friendship with the other class, second then the private data members of the class first
are permitted to be accessed by the public members of the class second.
e.g.: frie.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class first
{
private:
int firstnum;
public:
friend class second;
first(int i)
{
firstnum=i;
}
};
class second
{
public:
void showdata(first f)
{
cout<<"The value is:"<<f.firstnum;
}
};
void main()
{
first f(10);
second s;
clrscr();
s.showdata(f);
getch();
}
Constructor
Constructor is a special member function which enables an object to initialize
itself when it is created. This is known as automatic initialization of object. It is called
constructor because it construct the values of data members of the class.
The constructor function has some special characteristics...
1. They should be declared in the public section.
2. They are activated automatically when the objects are created.
3. They do not have return types, not even void and therefore they cannot return values.
4. They cannot be inherited though a derived class can call the base class constructor.
5. Like other c++ functions, they can have default arguments.
6. Constructors cannot be virtual.
7. We cannot refer to their addresses.
8. An object with a constructor cannot be used as a member of a union.
9. They make implicit calls to the operators new and delete when memory allocation is
required.
Declaration
Syntax:
class user defined name
{
private:
members;
public:
user name();
protected:
members;
};
user name::user name()
{
body of the function;
}
The constructor name and class name must be same.
A constructor is invoked automatically under the following circumstances.
1. The constructor is called before main () starts for execution.
2. Whenever an object is created in any one of the following ways.
1. Global variable.
2. Local variable.
3. Static variable
3. An auto variable of class is defined within a block and the location of its definition is
reached.
4. A temporary instance of class is to be created.
5. during use of the dynamic memory allocation operator new.

Types of constructors
1. Default constructor
2. Parameterized constructor
3. Copy constructor
4. Overloaded constructor
1. Default constructor
A constructor that accepts no parameter is called as default constructors... It is a
special member function which is invoked automatically without any arguments for
initializing the objects of a class
Syntax:
class user defined name
{
private:
datas;
public:
methods( user name);
protected:
datas;
};
user name:: user name()
{
body of the function;
}
e.g.: defcon.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class sample
{
private:
int a,b;
public:
sample()
{
a=10;
b=20;
}
void show()
{
cout<<"A="<<a<<endl<<"B="<<b;
}
};
void main()
{
sample s;
clrscr();
s.show();
getch();
}
2. Parameterized constructor
The constructor that takes arguments is called as parameterized constructor.
Syntax:
class user defined name
{
private:
datas;
public:
user defined name( arg1, arg 2);
protected:
datas;
};
user defined name:: user defined name ( arg 1, arg2)
{
body of the function;
}
e.g.: paracon.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class sample
{
private:
int a,b;
public:
sample(int x,int y)
{
a=x;
b=y;
}
void show()
{
cout<<"A="<<a<<endl<<"B="<<b;
}
};
void main()
{
sample s(20,30);
clrscr();
s.show();
getch();
}
3. Copy constructor
Constructor which takes a reference to an object of the same class as itself as an
argument is called as copy constructor.
It is always used when the compiler has to create a temporary object of a class
object. It is used in the following situations.
1. The initialization of an object by another object of the same class.
2. Return of an object as a function value.
3. Stating the object as by value parameters of a function.
Syntax:
class name::class name ( class name & ptr)
{
body of the function;
}
where
class name - user defined name
ptr - pointer to a class object.
e.g.: copcon.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class fibonacci
{
private:
unsigned long int f0,f1,fib;
public:
fibonacci()
{
f0=0;
f1=1;
fib=f0+f1;
}
fibonacci(fibonacci &ptr)
{
f0=ptr.f0;
f1=ptr.f1;
fib=ptr.fib;
}
void increment()
{
f0=f1;
f1=fib;
fib=f0+f1;
}
void display()
{
cout<<fib<<"\t";
}
};
void main()
{
fibonacci number;
int i;
clrscr();
for(i=0;i<=15;i++)
{
number.display();
number.increment();
}
getch();
}
4. over loaded constructor
Constructors can be overloaded by passing different no of arguments or different
type of arguments.
E.g. overcon.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class sample
{
private:
int a,b;
public:
sample()
{
a=10;
b=20;
}
sample(int x,int y)
{
a=x;
b=y;
}
void show()
{
cout<<"A="<<a<<endl<<"B="<<b<<endl;
}
};
void main()
{
sample s,s1(30,40);
clrscr();
s.show();
s1.show();
getch();
}

Destructor
A destructor is a function that automatically executes when an object is
destroyed. A destructor function gets executed whenever an instance of the class to
which it belongs goes out of existence. The primary usage of destructor function is to
release space on the heap. A destructor may be invoked explicitly.
Syntax rules
1. A destructor function name is the same as that of the class it belongs except that the
first character of the name must be tilde (~).
2. It is declared with no return types.
3. It cannot be declared static, constant, or volatile.
4. It takes no argument and therefore cannot be overloaded.
5. It should have public access in the class declaration.
Syntax;
class user defined name
{
private:
datas;
public:
user name();
~ user name();
protected:
datas;
};
It is invoked under the following circumstances.
1. after the end of the main for all static, local to main and global instances of class.
2. At the end of each block containing the auto variable of class.
3. At the end of each function containing an argument of class.
4. To destroy any unnamed temporaries of class after their use. When an instance of
class allocated on the is destroyed via delete.
eg:dest.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
#include<string.h>
class book
{
private:
int bookno;
char bname[20];
public:
book()
{
bookno=10;
strcpy(bname,"c++ courseware");
}
~book()
{
strcpy(bname," ");
cout<<"Destructor invoked";
}
void showdetail()
{
cout<<"Book no:"<<bookno<<endl;
cout<<"Book name:"<<bname<<endl;
}
};
void main()
{
book b;
clrscr();
b.showdetail();
getch();

Inheritance
The mechanism of deriving a new class from an existing base class is known as
inheritance... The old class is referred to as base class and the new one is called as the
derived class. The derived class inherits same or all the properties from the base class.
Inheritance supports the concept of reusability.
There are five types of inheritance.
1. Single inheritance
2. Multiple inheritances
3. Multi level inheritance.
4. Hybrid inheritance
5. Heirarchical inheritance.
Defining derived class
Syntax:
class derived class name : visibility mode base class name
{
members of derived class;
};
e.g.: 1
class abc:public xyz
{
members of abc;
};
e.g. 2:
class abc:private xyz
{
members of abc;
};
Making a private member inheritable
Private member of a base class cannot be inherited and therefore it is not
available for the derived class. directly.
C++ provides a third visibility mode protected which serve a limited purpose in
inheritance.
A member declared as protected is accessible by the member functions within its
class and any class immediately derived from it. It cannot be accessed by the functions
outside these two classes.
Visibility of inherited members
Base class Visibility Derived class visibility

Public derivation Private derivation

1. Private not inherited not


inherited
2. Protected protected private
3. Public public private
1. Single Inheritance
A derived class with only one base class is called single inheritance

B
A – Base class
B – Derived class
E.g.: Inherit1.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class emp
{
protected:
int eno;
char name[20];
public:
void getdetails()
{
cout<<"Enter eno:";
cin>>eno;
cout<<"Enter name:";
cin>>name;
}
void putdetails()
{
cout<<"Employee no:"<<eno<<endl;
cout<<"Employee name:"<<name<<endl;
}
};
class emp1:public emp
{
private:
float salary;
public:
void getsal()
{
cout<<"Enter salary:";
cin>>salary;
}
void putsal()
{
cout<<"Basic salary:"<<salary;
}
};
void main()
{
emp1 e;
clrscr();
e.getdetails();
e.getsal();
e.putdetails();
e.putsal();
getch();
}

2. Multiple Inheritances
A multiple inheritance is a one which has two base classes and one derived class.

` A B

A & B – base class


C- Derived class C
Eg:inherit2.cpp
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
class M
{
protected:
int m;
public:
void getm(int x)
{
m=x;
}
};
class N
{
protected:
int n;
public:
void getn(int y)
{
n=y;
}
};
class P:public M,public N
{
public:
void display()
{
cout<<"M="<<m<<endl;
cout<<"N="<<n<<endl;
cout<<"m*n="<<m*n;
}
};
void main()
{
P a;
clrscr();
a.getm(10);
a.getn(20);
a.display();
getch();
}

3.Multilevel
A multilevel inheritance is a one which has one base class and a derived class,
and from that derived class another derived class and so on.

A (Derived Class of A)

(Derived Class of B)
B
(Derived Class of c)
e.g.: inherit3.cpp
#include<iostream.h> C
#include<iomanip.h>
#include<conio.h>
class student
{
protected:
int rollno;
public:
void getno(int a)
{
rollno=a;
}
void putno()
{
cout<<"Rollno"<<rollno<<endl;
}
};
class test: public student
{
protected:
float theory,practical;
public:
void getmarks(float x, float y)
{
theory=x;
practical=y;
}
void putmarks()
{
cout<<"Theory="<<theory<<endl;
cout<<"Practical="<<practical<<endl;
}
};
class result:public test
{
protected:
float total;
public:
void display()
{
total=theory+practical;
putno();
putmarks();
cout<<"Total="<<total<<endl;
}
};
void main()
{
result s1;
clrscr();
s1.getno(10);
s1.getmarks(98.50,89.50);
s1.display();
getch();
}

4. Hybrid inheritance
It is a combination of multiple and multilevel inheritance.

B C

EG:inherit4.cpp
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
class student
{
protected:
int rollno;
public:
void getno()
{
cout<<"Enter rollno:";
cin>>rollno;
}
void putno()
{
cout<<"Rollno:"<<rollno<<endl;
}
};
class test: public student
{
protected:
float theory,practical;
public:
void getmarks()
{
cout<<"Enter theory marks:";
cin>>theory;
cout<<"Enter Practical Mark:";
cin>>practical;
}
void putmarks()
{
cout<<"Marks obtained:"<<endl;
cout<<"Theory="<<theory<<endl;
cout<<"Practical="<<practical<<endl;
}
};
class sports
{
protected:
float score;
public:
void getscore()
{
cout<<"Enter sports mark:";
cin>>score;
}
void putscore()
{
cout<<"Sports mark:"<<score<<endl;
}
};
class result: public test, public sports
{
protected:
float total;
public:
void display()
{
total=theory+practical+score;
putno();
putmarks();
putscore();
cout<<"Total marks="<<total<<endl;
}
};
void main()
{
result s1;
clrscr();
s1.getno();
s1.getmarks();
s1.getscore();
s1.display();
getch();
}

5. Hierarchical inheritance
A base class with several derived class is known as hierarchical inheritance.

B C D

E.g.: inherit5.cpp
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
class dept
{
private:
int dno;
char dname[10];
public:
void get()
{
cout<<"Enter dept no:";
cin>>dno;
cout<<"Enter dept name:";
cin>>dname;
}
void show()
{
cout<<"Dept number:"<<dno<<endl;
cout<<"Dept Name:"<<dname<<endl;
}
};
class emp: public dept
{
private:
int eno;
char ename[10];
public:
void get()
{
dept ::get();
cout<<"Enter eno:";
cin>>eno;
cout<<"Enter ename:";
cin>>ename;
}
void show()
{
dept ::show();
cout<<"Eno:"<<eno<<endl;
cout<<"Ename:"<<ename<<endl;
}
};
class salary:public dept
{
private:
int bs;
public:
void get()
{
cout<<"Enter basic pay:"<<endl;
cin>>bs;
}
void put()
{
cout<<"Basic pay:"<<bs<<endl;
}
};
void main()
{
emp e;
salary s;
clrscr();
e.get();
e.show();
s.get();
s.put();
getch();
}

Abstract class
An abstract class is one that is not used to create objects. An abstract class is
designed only to act as a base class.
Eg: Multiple inheritances
Polymorphism
It simply means one name multiple forms. There are two types of
polymorphism.
1. Compile time polymorphism
2. Run time polymorphism
1. Compile time polymorphism
It is also known as early binding or static binding or static linkage.
When a function is called through the object the C++ compiler determines which
function is used based on the parameters passed to the function or the function’s return
type. This happens during compilation time and this process is called as early binding.
E.g.;
Function overloading and operator overloading.
2. Runtime polymorphism
It is also known as late binding or dynamic binding.
Some time the type of the object does not known compilation time when the
objects are created dynamically at run time. In these cases the functions are binded
with the objects at runtime. This type of binding is called as late binding.
This is achieved by using virtual function.
Virtual function
Virtual function is used to achieve run time polymorphism. A virtual function is
a function that is declared as virtual in a base class and is redefined in the derived class.
To make a function as virtual, it should be preceded by the keyword “virtual.” A
function is declared as virtual because its execution depends on the context, which is
not known at the time of compilation.
Eg:poly1.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class baseA
{
public:
void display()
{
cout<<"Base class diplay function"<<endl;
}
};
class deriA:public baseA
{
public:
void display()
{
cout<<"Derived class display function"<<endl;
}
};
void main()
{
baseA b1;
baseA *b2;
b2=new deriA;
clrscr();
b1.display();
b2->display();
getch();
}
e.g.: 2 Poly2.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class base
{
public:
void display()
{
cout<<"Display base"<<endl;
}
virtual void show()
{
cout<<"Show base"<<endl;
}
};
class derived:public base
{
public:
void display()
{
cout<<"Display derived"<<endl;
}
void show()
{
cout<<"Show derived"<<endl;
}
};
void main()
{
base B;
derived D;
base *bptr;
clrscr();
bptr=&B;
bptr->display();
bptr->show();
bptr=&D;
bptr->display();
bptr->show();
getch();
}
Note
Run time polymorphism is achieved only when a virtual function is accessed
through a pointer to the base class.
Rules for virtual function
1. The virtual function must be member of some class.
2. They cannot be static members.
3. They are accessed by using object pointers.
4. A virtual function can be a friend of another class.
5. A virtual function in a base class must be defined, even though it may not be used.
6. The prototypes of the base class version of a virtual function and all the derived class
versions must be identical... If the two functions with the same name have different
prototype, c++ considers them as overloaded function, and the virtual function
mechanisms is ignored.
7. We cannot have virtual constructors, but we can have virtual destructors.
8. While a base pointer can point to any type of the derived class object, the reverse is
not true. That is, we cannot use a pointer to a derived class to access an object of the
base type.
9. When a base pointer points to a derived class, incrementing or decrementing it will
not make it to point to the next object of the derived class. It is incremented or
decremented only relative to its base type. Therefore we should not use this method to
move the pointer to the next object.
10. If a virtual function is defined in the base class, it need not be necessarily redefined
in the derived class. In such cases, calls will invoke the base function.
Operator Overloading
Definition
The mechanism of giving special meanings to an operator is known as operator
overloading. We can overload all the c++ operators except the following.
. - dot operator
.* - pointer to member operator
:: - scope resolution operator
sizeof - size of operator
conditional operator
Defining operator overloading
Syntax:
return type class name::operaor op(argument list)
{
body of the function;
}
Where return type is the type of the value returned by the specified operations and op is
the operator being overloaded.
e.g.:
Rules for overloading operators
1. Only existing operators can be overloaded. New operators cannot be created.
2. The overloaded operator must have at least one operand that is of user defined type.
3. We cannot change the basic meaning of an operator.
4. Overloaded operators follow the syntax rules of the original operators. That cannot
be overridden.
5. There are some operators that cannot be overloaded.
6. Operator function must be either friend function or member function. Unary
operators, overloaded by means of a member function, take no explicit arguments and
return no explicit values. But those overloaded by means of a friend function take one
reference argument.
e.g.:
vector operator -(); //unary minus
friend vector operator - ( vector); // unary minus
7. Binary operator overloaded through a member function take one explicit argument
and those which are overloaded through a friend function take two explicit arguments.
E.g.:
vector operator +(vector); // addition
friend vector operator + ( vector, vector) ; // addition
vector operator - ( vector &a); //subtraction
int operator ==(vector); //comparison
friend int operator ==(vector, vector) // comparison.

8. When using binary operators overloaded through a member function, the left hand
operand must be an object of the relevant class.
9. Binary arithmetic operators such as +, -, *, and / must explicit return a value. They
must not attempt to change their own arguments.
10. We cannot use friend functions to overload certain operators. However member
functions can be used to overload them.
= - assignment operator
() - Function call operator
[ ] - subscripting operator.
-> - class member access operator
Process of overloading involves the following steps
1. First create a class that defined the data typo that is to be used in the overloading
operation.
2. Declare the operator function operator op() in the public part of the class. It may be
either a member function or a friend function.
3. Define the operator function to implement the required operations.
Overloading unary operator
E.g.: over1.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class space
{
private:
int x,y,z;
public:
void getdata(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void display()
{
cout<<x<<" "<<endl;
cout<<y<<" "<<endl;
cout<<z<<endl;
}
void operator -()
{
x=-x;
y=-y;
z=-z;
}
};
void main()
{
space s;
clrscr();
s.getdata(10,-20,30);
cout<<"S:";
s.display();
-s;
cout<<"S:";
s.display();
getch();
}
Over loading binary operator
E.g.: over2.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class complex
{
private:
float x,y;
public:
complex(){}
complex(float real,float imaginary)
{
x=real;
y=imaginary;
}
complex operator +(complex c)
{
complex temp;
temp.x=x+c.x;
temp.y=y+c.y;
return(temp);
}
void display()
{
cout<<x<<"+j"<<y<<endl;
}
};
void main()
{
complex c1,c2,c3;
clrscr();
c1=complex(2.5,3.5);
c2=complex(1.6,2.7);
c3=c1+c2;
cout<<"C1=";c1.display();
cout<<"C2=";c2.display();
cout<<"C3=";c3.display();
getch();
}
Program for overloading == operator
E.g.: over3.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
#include<string.h>
class string
{
private:
char str[10];
public:
void get()
{
cout<<"Enter the string:"<<endl;
cin>>str;
}
friend int operator ==(string s1,string s2)
{
if(strcmp(s1.str,s2.str)==0)
return 1;
else
return 0;
}
};
void main()
{
string s1,s2;
clrscr();
s1.get();
s2.get();
if(s1==s2)
cout<<"Both string are equal";
else
cout<<"Both string are not equal";
getch();
}
Files
In c++ to handle file I/O, special classes have already been defined in the header
file fstream.h.
The following classes are used to handle file I/O operations
1. ifstream - used whenever the user wishes to read a file.
2. ofstream - used to write the data to the file.
3. fstream - both the read and write operation in the file.

Create and Write To a File


To create a file, use either the ofstream or fstream class, and specify the name of the file.

To write to the file, use the insertion operator (<<).

Example
#include <iostream>
#include <fstream>

void main() {
// Create and open a text file
ofstream MyFile("filename.txt");

// Write to the file


MyFile << "Files can be tricky, but it is fun enough!";

// Close the file


MyFile.close();
getch();
}
Read a File
To read from a file, use either the ifstream or fstream class, and the name of the file.

Note that we also use a while loop together with the getline() function (which belongs to
the ifstream class) to read the file line by line, and to print the content of the file:

Example:
// Create a text string, which is used to output the text file
string myText;

// Read from the text file


ifstream MyReadFile("filename.txt");

// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}

// Close the file


MyReadFile.close();

You might also like