Oop Notes
Oop Notes
DEPARTMENT
Chapter1
Principles of object oriented programming
• pop vs oop:
POP OOP
class.
"protected".
operators.
and protected.
security increases.
Data sharing Global data is shared among the Data is shared among the
member functions.
"friend".
C#.NET.
Abstraction: Data abstraction is one of the most essential and important features
of object-oriented programming in C++. Abstraction means displaying only
essential information and hiding the details. Data abstraction refers to providing
only essential information about the data to the outside world, hiding the
background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the speed of the car or applying brakes will
stop the car but he does not know about how on pressing accelerator the speed is
actually increasing, he does not know about the inner mechanism of the car or the
implementation of accelerator, brakes etc in the car. This is what abstraction is.
Example: Suppose we have to write a function to add some integers, some times
there are 2 integers, some times there are 3 integers. We can write the Addition
Method with the same name having different parameters, the concerned method
will be called according to parameters.
• Sub Class: The class that inherits properties from another class is called Sub
class or Derived Class.
• Super Class:The class whose properties are inherited by sub class is called
Base Class or Super class.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some of
the code that we want, we can derive our new class from the existing class. By
doing this, we are reusing the fields and methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
• Structure of C++:
return 0;
}
#include<iostream>
int x; // Global x
int main()
return 0;
#include<iostream.h>
class A
public:
// Only declaration
void fun();
};
void A::fun()
int main()
A a;
a.fun();
return 0;
• New operator:
A new operator is used to create the object while a delete operator is used to delete
the object. When the object is created by using the new operator, then the object
will exist until we explicitly use the delete operator to delete the object. Therefore,
we can say that the lifetime of the object is not related to the block structure of the
program.
Syntax
The above syntax is used to create the object using the new operator. In the above
syntax, 'pointer_variable' is the name of the pointer variable, 'new' is the
operator, and 'data-type' defines the type of the data.
Example 1:
1. int *p;
2. p = new int;
Example 2:
1. float *q;
2. q = new float;
• Delete operator:
1. delete pointer_variable;
In the above statement, 'delete' is the operator used to delete the existing object,
and 'pointer_variable' is the name of the pointer variable.
In the previous case, we have created two pointers 'p' and 'q' by using the new
operator, and can be deleted by using the following statements:
1. delete p;
2. delete q;
String:
• Just like characters, strings in C++ are used to store letters and digits.
Strings can be referred to as an array of characters as well as an individual
data type.
• It is enclosed within double quotes, unlike characters which are stored
within single quotes. The termination of a string in C++ is represented by the
null character, that is, ‘\0’. The size of a string is the number of individual
characters it has.
• In C++, a string can be declared in the following ways:
• char name[30] = ‘’Hello!”; // The compiler reserves 30 bytes of memory for
the string.
• char name[] = “Hello!”; // The compiler reserves the required amount of
memory for the string.
• char name[30] = { ‘H’ , ’e’ , ’l’ , ’l’ , ’o’};; // This is how a string is
represented as a set of characters.
string name = “Hello” // The compiler reserves 32 bytes of memory
Structure:
A structure is a user-defined data type in C/C++. A structure is a collection of different
data types elements.
The ‘struct’ keyword is used to create a structure. The general syntax to create a
structure is as shown below:
struct structureName{
member1;
member2;
member3;
.
.
.
memberN;
};
struct structureName{
member1;
member2;
member3;
.
.
.
memberN;
};
struct student
int roll_no;
char name[20];
float marks;
void get();
void show();
};
Chapter no2
Classes and Objects
2.1 Classes and Objects:
• Classes:
Variable declarations;
Function declarations;
public:
Variable declarations;
Function declarations;
};
Example:
class person
{
char name[10]; //variable declaration
int age; Il private by default
public:
void getdata(); //function declaration
void putdata();
};
• Access Specifiers:
Acess specifiers idefine the access rights for the statements or
functions that follow it
until another access specifier or till the end of a class. The three
types of access specithers are
1. private
2.upublic
3.protected
Syntax
class Base
{
private:
// private members go here
public:
// public members go here
protected
// protected members go here
};
private:
• The members declared as "private" can be accessed only within the
same class and not from outside the class.
public:
• The members declared as "public" are accessible within the class
as well as from outside the class.
protected:
• The members declared as "protected" cannot be accessed from
outside the class, but can be accessed from a derived class. This is
used when inheritance is applied to the members of a class.
• Creating Objects:
• The definition of class does not define any objects but only
specifies what that class contains.
• Once class has been defined, we can create variables of that type
by using the class name.
• Objects can be defined in similarly way as structure is defined.
Syntax:
class name variable name;
• Let's say for the defined class Sample, objects for that class can be
defined as:
Example:
• Here, two objects (objl and obi2 of Sample class are defined.
Example:
class Item
{
int number
float cost;
public:
void getdata(inta,float b);
void putdata(void);
};
void main0
{
Item x.y,y,z; //memory for xy,z is created
}
• Example
x.qetdata(50,65.5):
xputdata0: //display the values of data members.
function body
}
• #include<iostream.h>
#include conio.h> Enter the value of a and b:
class Add
{
int a, b, total;
public:
void getdata();
void display():
};
void main ()
{
Add a;
a.getdata ();
a.display();
getch ();
Syntax
class class_name
{
public:
return_type function_name(argument(s))
{
function body;
}
#include<iostream.h>
#include<conio.h>
class Add
{
int a, b,total;
public:
void getdata0
{
cout<<,"\n Enter the value of a and b";
cin> >a>>b;
}
void display0
{
total a+b;
cout<<"\n the sum of a and b="<<total;
}
void main()
{
Add a;
a.getdata();
a.display():
getch();
}
• Syntax:
A) For defining static member variable inside the
class:
static data_type variable name; Example:
static int count;
#include<iostream.h>
#include<conió.h>
class item
{
public:
void getdata(int a)
{
number=a;
count++
}
void getcount(void)
{
cout<<"count:";
cout< <count< <"\n":
}
};
int item ::count //count defined
void main0
{
item w,x,y //count is initialized to zero
w.getcount(); //display count
x.getcount();
y.getcount(): //getting data into object a
w.getdata(100); //getting data into object b
x.getdata(200);
y.getdata(300); //getting data int object c
cout<<"After reading data "<<"\n
w.getcount( );
x.getcount():
y.getcount():
getch();
}
• Syntax
class_name::function_name0;
#include <iostream.h>
class test
{
int code; //static member variable
static int count;
public:
void setcode()
{
code=++count;
}
void showcode()
{
cout<<"Object number:"<<code< <end;
}
{
cout<<"Count:"< <count< <endl;
}
};
int test::count //definition of static data member
void main0
{
test t1,t2;
t1.setcode ();
t2.setcode ():
Friend Function:
• A friend function of a class is defined outside that class' scope.
• It has the right to access all private and protected members of
class.
• Syntax:
class class_name
{
public:
Write a program to find the mean value of a given number using friend
function. [W-13
#include<iostream.h> O
#include< conio.h>
class base
{
int val1,val2;
public:
void get( )
{
cout<< "Enter two values:";
cin>> val1>>yal2;
return float(ob.val1+ob.val2)/2;
}
void main()
{
clrscrO:
base ob;
ob.get0:
cout<<"\n Mean value is:"< <mean(obj); //call to friend function
getch0:
}
2.3 Array:
2.3.1Array of objects:
• Array is a collection of variables of same data; similarly array of
objects is collection of more than object of same class.
• We can have arrays of variables that are of the type class. Such
variables are called array of objects.
• Syntax:
class class_name
{
}object name[sizej;
OR
Class class_name
{
};
void main()
{
class name objectname[size];
}
Example:
class employee
{
char name[30];
float age;
public:
void getdata();
void putdata0;
};
•
Example: Write a program for addition of two objects. IS-10, W-
13]
#include<iostream.h>
#include <conio.h>
class Addition
{
int a,b;
public:
void getno(intx,int y)
{
a-x
b=y
}
void putno()
{
cout<<"first no:"< <a;
cout<<"second no:"< <b;
}
void sum(Addition, Addition); //objects as function argument
cout<<"A2:"
a2.putno();
cout<<"A3:"
a3.putno():
getch():
}
2.4Concepts of Constructors:
• A Constructor is a special member function of a class whose task is
to initialize the objects of its class.
• Uniike normal functions, constructors have specific rules for how
they must be named:
class class_name
{
Access Specifier:
Member variables;
Member functions;
public:
Class name( arguments) // Constructor name is same as class
name
{
Body of constructor;
}
public:
circle () // default constructor
{
radius=0;
}
int main()
{
circle c1; // default constructor called
return 0;
}
Types of Constructor:
There are three types of constructors
1. Default Constructor
2. Parameterized Constructor
3 Copy Constructor
circle() .
{
radius = 0;
}
2. Parameterized Constructor: A constructor that receives
arguments/parameters is called
parameterized constructor'
circle(double r)
{
radius =r;
}
1. Default Constructoor
Default Constructoor is the constructor which doesn't take any
argument. It has no parameter.
Syntax
class_name ()
{
Constructor Definition
}
Example:
class Cube
{
int side;
public:
Cube()
{
side=10;
}
int main()
{
Cube c;
cout << c.side;
}
Note:
In this case, as soon as the object is Created the constructor is called
which initializes its data members.
A default constructor is so important for inialization of object
members, that even if we do not
define a constructor explicitly, the compier WIll provide a default
constructor implicitly.
2. Parameterized Constructor:
• Constructor which has arguments that constructor is called as'
Parameterized Constructor'.
• It is same as normal function take arguments just put arguments
in the constructor and use them to initialize objects.
• Syntax:
class class_name
{
Access Specifier
Member Variables;
Member Functions;
public: .
class-name(parameter1, parameter2,..,parameter n)
{
/ / Constructor code
}
class time
{
private:
int hrs, min, sec;
Public:
time ( int h, int m, int s) // <-- Parameterized constructor with three
arguments
{
hrs= h;
min=m;
sec =s;
}
void disp()
{
cout<<"HRS: "<<hrs<<endl;
cout<< "MIN: "<<min< <endl;
cout<<"SEC: "<<sec< <endl;
}
};
void main ()
{
cout<< "implicit cal:"<<endl;
time t1 (10, 20, 30): //implicit call
t1.disp();
note:
Above program will pass initial value as arguments to constructor time
We can pass this values to constructor by two ways
1. By calling constructor implicitly:
time t1 (10, 20, 30);
2.By calling constructor explicitly:
time t2= time (100, 200, 300);
3. Copy constructor:
#include<iostream.h>
#include<conio.h>
class abc
{
private:
int a,b;
public:
abc()
{
a= 2;
b =4;
}
abc(abc &X)
{
a= X.a
b =X.b;
}
void disp()
{
cout<<"a="<<a<<"b="< <b<<endi;
}
void main()
{
abc obj1;
obj1.disp():
abc obj2(obj1);
obj2.disp();
getch();
}
public:
class name() // default constructor
{
// Constructor code
}
{
// Constructor code
}
{
// Constructor code
}
};
Example:
#include <iostream.h> Output:
#include <conio.h>
class abc
{
public:
int a, b;
void disp()
{
Cout << "a= "< <a<<" b= "<<b<<"\n";
}
void main()
{
abc A;
abc A1(10);
abc A2(15, 20);
abc A3(A2);
A2.disp();
cout << "\ncopy constructor value:";
A3.disp();
getch();
}
{
// Constructor code
}
};
class abc
{
int a; b
float b;
public:
a= x;
b =y;
}
void display()
{
cout<<"\n\n a: "<<a;
cout<<"n b: "<<b;
}
};
void main()
{
clrscrO:
abc obj
abc obj2(1,60);
getch();
}
#include<conio.h>
#include <iostream.h>
class simpleinterest
{
private:
float principle, numberOfyears, rateOfinterest;
public: ,
simplehterest(float p, float n, float r = 11.5)
{
principle = p;
numberOtyears = n;
rateOflnterest= r;
}
void displaySimplelnterest0
{
float SI= (principle* numberOfyears *rateOfinterest)/100;
coute <<"n Simple Interest: " <<SI;
}
};
void main()
clrscr():
cout<<"nObj1 \n":
simpleinterest obji(1000,2);
obj1.displaySimplelnterest();
cout<<"\nObj2 :\n"
simplelnterest obj2(1000, 2, 10);
obj2.displaySimplelnterest();
getch();
}
2.6 Destructor:
~class name ()
{
// body of destructor
}
class Marks
{
C++ Object created
public:
int maths;
int science;
Marks()
{
cout< < "\n Inside Constructor"< <endl;
cout< <"\n C++ Object created"<<endl;
}
~Marks() //Destructor
{
cout < "n Inside Destructor"< <end;
cout «< "n C++ Object destructed"<<endl;
}
};
void main()
{
clrscrO;
cout<<"n Enter blöck m1";
getch();
Chapter No3
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important feature of Object Oriented
Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class or child class.
Super Class:The class whose properties are inherited by sub class is called Base Class or Super
class,parent class
• With public visibility mode derived class can inherit all public member variables and
public member functions of base class.
Syntax
class B : public A
{
Members of class B
}
• With private visibility mode derived class cannot inherit any member variables and
member functions of base class even if they are declared as public or private.
• Syhtax
Members of class B
}
• The public makes all members accessible to all functions of program and loses the
data hiding
• The private does not allow accessing any members directly from the program.
• The protected solves this problem by making members protected accessible to access
from the same class and next immediate derived class
• The declared protected members cannot access by any other class from the program.
• Syntax:
class A
{
protected:
member variables;
member function;
}
class B: public A
{
Members of class B
3.3.1Single Inheritance:
..........
};
...........
};
Example
#include <iostream.h>
public:
int x;
void getdata()
cin >> x;
};
private:
int y;
public:
void readdata()
cin >> y;
void product()
};
int main()
a.getdata();
a.readdata();
a.product();
return 0;
} //end of program
Multilevel inheritance represents a type of inheritance when a derived class is a base class for
another class.
Example: Here, the derived class Rectangle is used as a base class to create the derived class
called ColorRectangle. Due to inheritance the ColorRectangle inherit all the characteristics of
Rectangle and Shape and add an extra field called rcolor, which contains the color of the
rectangle.
Syntax:Multilevel Inheritance :
...........
};
...........
};
...........
};
Program:
#include <iostream>
public:
int x;
void getdata()
cin >> x;
};
public:
int y;
void readdata()
cin >> y;
};
private:
int z;
public:
void indata()
cin >> z;
void product()
};
int main()
a.getdata();
a.readdata();
a.indata();
a.product();
return 0;
} //end of program
Syntax:
class A
..........
};
class B
...........
};
...........
};
// multiple inheritance.cpp
#include <iostream.h>
class A
public:
int x;
void getx()
cin >> x;
};
class B
public:
int y;
void gety()
cin >> y;
};
public:
void sum()
};
int main()
obj1.getx();
obj1.gety();
obj1.sum();
return 0;
} //end of program
• When several classes are derived from common base class it is called hierarchical
inheritance
• .In C++ hierarchical inheritance, the feature of the base class is inherited onto more
than one sub-class
• .For example, a car is a common class from which Audi, Ferrari, Maruti etc can be
derived.
Syntax:
..............
};
...........
};
...........
};
...........
};
Example:
#include <iostream>
public:
int x, y;
void getdata()
};
public:
void product()
};
public:
void sum()
};
int main()
obj1.getdata();
obj1.product();
obj2.getdata();
obj2.sum();
return 0;
} //end of program
• The inheritance in which the derivation of a class involves more than one form of any
inheritance is called hybrid inheritance.
Syntax:
class A
.........
};
class B : public A
..........
};
class C
...........
};
...........
};
Example:
#include <iostream>
class A
public:
int x;
};
class B : public A
public:
x = 10;
};
class C
public:
int y;
y = 4;
};
public:
void sum()
};
int main()
obj1.sum();
return 0;
} //end of program
In above fig, properties of Base class are inherited via Derived/base class I and Derived/base
class.2 to the Derived class.
• Fiqure above explains that the properties of grandparent class can be inherited by the
child class via two parents class and sometimes grandparent can directly accessible
to child.
• Here, Child class gets confused as the same property Is inherited by him twice and
this introduces ambiguity which must be avoided.
• To help child class we have to declare Dase cias5 as virtual Class so that properties
of that class becomes virtual and child class won't pay attention to those properties
assuming as virtual .
• When a class is made virtual base class C++ takes necessary action for
copy of base class and that single copy inherited by child class action for making
only single copy of base class and that single copy inherited by child class.
Syntax:
class Base
{
public:
public member variables
public member function
private:
public member variables
public member function
};
};
};
public:
public member variables
public member function
private:
public member variables
public member function
};
Example:
#include<iostream.h>
#include<conio.h>
class base
{
public:
void show_a()
{
cout<< "In class a";
}
};
};
};
void main()
{
derived d;
d.show_a();
d.show_b():
d.show_c();
d.show_d();
getch();
}
• Abstract Class is a class which contains at least one Pure Virtual function in it.
• Abstract classes are used to provide an Interface for its sub classes.
• Classes inheriting an Abstract Class must provide definition to the pure virtual u
otherwise they will also become abstract class.
• Abstract class cannot be instantiated, but pointers and references of Abstract class
type can be created.
• Abstract class can have normal functions and variables along with a pure virtual
tunction.
• Classes inheriting an Abstract Class must implement all pure virtual functions, or else
they will become Abstract too.
Program
#tinclude<iostream.h>
#include <conio.h>
class Base //- ---Abstract base class Implementation of Virtual Function
{
public:
virtual void show() = 0; //Pure Virtual Function
};
{
public:
void show()
};
void main()
{
Base obj; // we cannot create object of abstract class. Gives compile Time Error
Base *b;
Derived d;
b=&d;
b->show():
getch();
Syntax
variable X = argD;
basel(argB1) invokes the base constructor base1() and base2(argB2) invokes another base class
constructor base2().
The Derived_ constructor( ) supply the values i.e. argB1, argB2 to base1() and base2() and to
one of its own variables X.
argB1=5
argB2=12
argD=7
#include <<iostream.h»
#irnclude<< conio.h>>
class basel1
private:
int a;
public:
base1(int p)
a= p;
void show_b1()
};
class base2
private:
float b;
public:
base2(float q)
b =q;
void show_b2()
};
private:
int c,d;
public:
c=l;
d=m;
void show_d()
};
void main()
derived obj(27,3.14,200,5);
obj.show_b1();
obj.show_b2();
obj.show_d();
Chapter No4
4.1Concept of pointer:
• Pointer:
• Unlike other variables that hold values of a certain type, pointer holds the address of a
variable.
• For example, an integer variable holds an integer value, however an integer pointer holds
the address of a integer variable.
• Pointer declaration:
Here is the syntax to declare a pointer
data_type *poiter_name;
Let's consider with following example statement
int *ptr;
Here, in this statement
• ptr is the name of pointer variable
• The character asterisk (*) tells to the compiler that the identifier ptr should be declare as
pointer.
• The data type int tells to the compiler that pointer ptr will store memory address of
integer type variable.
• Finally, ptr will be declared as integer pointer which will store address of integer type
variable.
• Address operator:
After declaration of a pointer variable, we need to initialize the pointer with the valid
memory address; to get the memory address of variable “Address Of" (&) Operator is
used.
int main()
{
int x=10; //integer variable
int *ptrX; //integer pointer declaration
ptrX=&x; //pointer initialization with the address of x
cout<<”Value of x=”<<*ptrx;
cout<<”Address of x=”<<ptrx;
return 0;
}
• Pointer Arithmetic:
include<iostream.h>
#include<conio.h>
void main()
{
int i=3, *X;
X = &i;
cout<<"\nOriginal address in x = "<<x;
getch();
}
4.2Pointer to object:
• Pointer to object is pointer variable of the same class whose object is to be pointed to by
it.
• Syntax:
• To access individual members of object using pointer an operator called arrow operator (-
>)
abc obj;
Program:
#include<IOstream.h>
#include<conio.h>
#include <string.h>
class book
{
char book_title[20],author_name[20];
float price;
public:
void getdàta()
{
cout<<"\nEnter Book Title, Author Name & Price";
cin>>book_title> > author name> >price;
}
void putdata()
{
cout<<"\nBook Title:"< <book_title;
cout<<"\nAuthor Name:"<<author_name;
cout<<"\n Price:"< <price;
}
};
void main()
{
book b,*pt;,
ptr=&b;
ptr->getdat();
ptr->putdata();
getch0;
}
Program2:
#include<iostream.h>
#include <conio.h>
class birthday
{
public:
int day,month.year;
void getdata()
{
cout< <"\nEnter bdate (Day Month Year) :
cin>>day> > month> >year,
}
void putdata()
{
cout< <day<<"/"< <month< <"l"<<year
}
};
void main0
{
birthday b[5],*p;
p=&b[0];
for(int i=0;i<5;i++)
{
cout"\nEnter bday:";
p->getdata0;
p++;
}
p=&b[0];
for(i=0;i<5;i++)
{
cout<<"bday”;
p->putdata();
p++;
}
getch();
}
4.2.2 this pointer
• it is predefined pointer variable in every class.
• it is pointer to the current object i.e the object whose member (data/function) is currently
being accessed.
• when a member function is called this' pointer is automatically passed as an implicit
argument to that function.
• Syntax:
The keyword this is used to access the pointer to the current object. We have to use the
arrow operator (->) in order to access the members of the current object along with this
pointer.
• Program 1. Write a program to display rollno and name of student using ' this' pointer
#include<iostream.h»
#include<conio.h>
#include< string.h>
class student
{
public:
int n ,
char name[20];
void print0;
student(int n, char name[]);
};
void print0
{
cout<< "Roll no = "<<n< <endl;
çout<< "name = " <<name< <endl;
}
void main0
{
student s(6,"abc");
s.print();
getch();
}
4.2.3 pointer to derived class
#include<iostream.h>
class base
{
public:
int n1;
void show()
{
cout<<”\nn1 = “<<n1;
}
};
class derive : public base
{
public:
int n2;
void show()
{
cout<<”\nn1 = “<<n1;
cout<<”\nn2 = “<<n2;
}
};
int main()
{
base b;
base *bptr; //base pointer
cout<<”Pointer of base class points to it”;
bptr=&b; //address of base class
bptr->n1=44; //access base class via base pointer
bptr->show();
derive d;
cout<<”\n”;
bptr=&d; //address of derive class
bptr->n1=66; //access derive class via base pointer
bptr->show();
return 0;
}
4.3 Polymorphism:
4.3.1:Concept:
4.3.2.Types of polymorphism
• Function overloading allows you to use the same name for different functions, to
perform,either same or different functions in the same class.
• When there are multiple functions with same name but different parameters then these
functions are said to be overloaded.
1) Number of arguments:
• In this type of function overloading, we define two functions with same names but
different number of parameters of the same type.
void display (int x)
{
cout< <"x="< <x;
}
void display (int x; int y)
{
cout<<"x="<<x;
cout<<"y="< <y;
}
void main()
display (10)
display (10,20);
}
• In above example, display () function is overloaded to have one and two arguments.
• In this type of overloading, we define two or more functions with same name and same
number of parameters, but the type of parameter is different.
{
cout<<"x="<<X;
}
void display (float x, float y)
{
}
void main()
display (10);
display (10.10,20.10);
#include<iostream.h>
#include<conio.h>
int c;
c=a;
a=b;
b=c;
float c;
c=a;
a=b;
b=c;
void main()
int a,b;
float c,d;
clrscr();
cin>>a>>b;
cin>>c>>d;
void swap(a,b );
void swap(c,d);
getch();
• For example, we can make the operator (‘+’) for string class to concatenate two strings.
We know that this is the addition operator whose task is to add two operands.
• So a single operator ‘+’ when placed between integer operands , adds them and when
placed between string operands, concatenates them.
• For example,'+' operator can be overloaded to perform addition on various data types,
like for Integer, String (concatenation) etc.
• Can't redefine the meaning of a procedure. You cannot change how integers are
added.
• Member Function: Mermber function has no arguments for unary operator and
one for binary operator
• Friend Function: Friend function has only one argument for unary operator and
two for binary operator
#include<iostream.h>
#include<conio.h>
class complex {
int a, b;
public:
void getvalue()
complex t;
t.a = a + ob.a;
t.b = b + ob.b;
return (t);
void display() {
};
void main()
clrscr();
obj1.getvalue();
obj2.getvalue();
obj1.display();
obj2.display();
result.display();
getch();
• Arity (numbers of Operands) cannot be changed. Unary operator remains unary, binary
remains binary etc.
• Cannot redefine the meaning of a procedure. You cannot change how integers are added.
• This will need the use of a single pointer variable to refer to the objects of different
classes.
• Here, we use the pointer to base class tó refer to all the defived objects.
• .The compiler ignores the content of the pointer and chooses the member function that
matches the type of pointer. For this Virtual Functions are needed.
• Virtual functions allow us to create a list of base class pointers and call methods of any of
the derived classes without even knowing kind of derived class object.
• A Virtual function is a function in a base class that is declared using the keyword virtual.
• Defining in a base class a virtual function, with another version in a derived class, signals
to the compiler that we don't want static linking for this function.
4.5.1:Virtual Function:
• Supports to late binding in which function in base class is declared virtua! using keyword
virtual & overridden in each-derived class
• It is invoked through pointer a base class which points to object of derived class whose
function definition is used.
#include<iostream.h>
#include<conio.h>
class Base
{
public:
};
public:
void show()
{
cout <<"Derived Class";
}
void main0
{
Base *b;
Derived d;
b=&d
b->show()
getch();
• only the Base class Method's declaration needs the virtual keyword, not the definition.
• if a function is declared as virtual in the base class, it will be virtual in all its derived
classes.
• The base pointer can point to any type of the derived object but derived cannot.
• The "= 0" portion of a pure virtual function is also known as the pure specifier,
because it's what makes a pure virtual function "pure".
• The notation "= 0" is just there to indicate that the virtual function is a pure virtual
function,and that the function has no body or definition.
#include <iostream.h>
#include <conio.h>
class Base
{
public:
virtual void show() ; //Pure Virtual Function
};
void show()
{
}
void main()
{
Base *b;
Derived d;
b= &d
b->show0:
getch();
In Compile time Polymorphism, the call is In Run time Polymorphism, the call is
polymorphism where more than one methods Method overriding is the runtime
share the same name with different polymorphism having same method
parameters or signature and different return with same parameters or signature, but
It provides fast execution because the method to early binding because the method
Compile time polymorphism is less flexible flexible as all things execute at run
CHAPTER NO:5
FILE OPERATIONS
fstream new_file;
new_file.open(“newfile.txt”, ios::out);
➢ In the above example, new_file is an object of type fstream, as we know fstream is a class
so we need to create an object of this class to use its member functions. So we create
new_file object and call open() function. Here we use out mode that allows us to open the
file to write in it.
➢ Default Open Modes :
• ifstream ios::in
• ofstream ios::out
• fstream ios::in | ios::out
Example
ofstream new_file;
➢ Here, input mode and append mode are combined which represents the file is opened for
writing and appending the outputs at the end.
➢ As soon as the program terminates, the memory is erased and frees up the memory
allocated and closes the files which are opened.
➢ But it is better to use the close() function to close the opened files after the use of the file.
➢ Using a stream insertion operator << we can write information to a file and using stream
extraction operator >> we can easily read information from a file.
➢ Example of opening/creating a file using the open() function
#include<iostream>
#include <fstream>
int main()
fstream new_file;
new_file.open("new_file",ios::out);
if(!new_file)
else
return 0;
➢ Explanation
In the above example we first create an object to class fstream and name it
‘new_file’. Then we apply the open() function on our ‘new_file’ object. We give
the name ‘new_file’ to the new file we wish to create and we set the mode to ‘out’
which allows us to write in our file. We use a ‘if’ statement to find if the file
already exists or not if it does exist then it will going to print “File creation failed”
or it will gonna create a new file and print “New file created”.
#include <iostream>
#include <fstream>
int main()
fstream new_file;
new_file.open("new_file.txt",ios::out);
new_file.close();
return 0;
Output:
#include <iostream>
#include <fstream>
int main()
fstream new_file;
new_file.open("new_file_write.txt",ios::in);
if(!new_file)
else
char ch;
while (!new_file.eof())
new_file >>ch;
new_file.close();
return 0;
➢ Explanation:
In this example, we read the file that generated id previous example i.e. new_file_write.
To read a file we need to use ‘in’ mode with syntax ios::in. In the above example, we
print the content of the file using extraction operator >>. The output prints without any
space because we use only one character at a time, we need to use getline() with a
character array to print the whole line as it is.
➢ Writing to a file:
Example:
#include <iostream>
#include <fstream>
int main()
fstream new_file;
new_file.open("new_file_write.txt",ios::out);
if(!new_file)
else
new_file.close();
return 0;
➢ Explanation:
Here we first create a new file “new_file_write” using open() function since we wanted to
send output to the file so, we use ios::out. As given in the program, information typed
inside the quotes after Insertion Pointer “<<” got passed to the output file.
➢ You can detect when the end of the file is reached by using the member function eof()
which has prototype :
int eof();
➢ It returns non-zero when the end of file has been reached, otherwise it returns zero.
➢ Example:
ifstream fin ;
fin.open("master", ios::in | ios::binary);
{
cout << "End of file reached ! \n" ;
}
Example 2:
#include <iostream.h>
#include <fstream.h>
#include <assert.h>
int main(void)
fin >> data; // get first number from the file (priming the input statement)
assert(!fin.fail( ));
return 0;
5.3.2:file modes: