Object Oriented Programming Language (C++ Language)
Introduction to OOP:- OOP has been developed, based on real life itself, to easily and efficiently remove the problems associated with procedural programming. To achieve the OOP we can better design a Software and maintenance can be easy. We can remove ambiguity resulting in consistency of a software.
It provides maximum degree of cohesion by adding functionality to the existing code (with the help of a special feature, inheritance) without interfering with others. Inheritance and another feature, polymorphism, make the code easily re-usable and extensible.
In the Object Oriented Approach, data is treated as the most important part of the program and can be hidden to limit access and prevent mishandling.
Features of OOP:- There are five main features of OOP which plays vital role to implement the OOP in Programming language.
Classes:- A class is a prototype that defines the variables and the methods common to all objects of a certain kind, in other word a class is a user-defined data type which indistinguishable fro in-built types like int, char, etc.
A class is an abstraction of real world entities and implementation of an Abstract Data Type.
Variable declared/defined within class is called member-variable and function declared/defined within class is called member-function.
Benefits of Classes:- Classes provide the benefit of reusability. Software programmers use the same class over and orer again to create many objects.
Syntax to define a class:-
class class_name
{
private:
data_type member_name;
//declaration of member variables
public:
return_type function_name(parameters);
//declaration of member functions
};
Objects:- Objects are the fundamental runtime entities in an object-oriented system. Each object has some storage associated with it. The state of an object is determined by the values that are stored in memory. Objects are variables of a type described by a class. Objects are totally self-contained entities and are responsible for their own behavior. Objects are also called an Instance in some languages.
private: |
Instantiation -> |
Variables
Methods |
|
Class A | Object1 |
Benefits of Object:- Object provide the benefit of modularity and information hiding.
The main difference between Class and Object is that objects are tangible, but a class is always intangible. You can’t see a class but you can always see an object.
Syntax to create an object:-
class_name object_name;
Member-functions:- When a function declare/defined within a class it is said to be a member function of that class.
Encapsulation:- Packaging an object’s variables within the protective custody of its methods is called encapsulation. Typically, encapsulation is used to hide unimportant implementation details from other objects. Encapsulation allows program changes to be reliably made with limited effort. Abstraction and encapsulation are complementary concepts. In C++ encapsulation implies that each class should be partitioned into private, public or protected.
Polymorphism:- Polymorphism can be defined as the ability of related objects to respond to the same message with different, but appropriate, action. Polymorphism means the ability to take more than one form. For example, an operation may exhibit different behavior in different instances. The behavior depends upon the types of data used in the operation.
Polymorphism plays an important role in allowing objects having different internal structures to share the same external interface. Polymorphism is extensively used in implementing inheritance.
Inheritance:- Inheritance is a technique that allows new classes to be derived from existing classes such that the objects of the new class possess all the behaviors and attributes of the parent class. Thus the properties of a class can be inherited up to any number of levels. The process of deriving a new class from an existing class is known as subclassing. The parent class is called the superclass and the child class is known as the subclass or derived class.
Class A
private:
Variables
public:
Methods
Class X Class Y Class Z
Types of Inheritance:- The Inheritance can be mainly of two types i.e. private and public.
Private:- When a base class is privately inherited by a derived class, ‘public members’ of the base class become ‘private member’ of the derived class and therefore the public members of the base class can only be accessed by the member functions of the derived class. They are inaccessible to the objects of the derived class. A public member of a class can be accessed by its own objects using the dot (.) operator. The result is that no member of the base class is accessible to the objects of the derived class.
Public:- When the base class is publicly inherited, ‘public members’ of the base class become ‘public members’ of the derived class and therefore they are accessible to the objects of the derived class. In both the cases, the private members are not inherited and therefore, the private members of a base class will never become the members of its derived class.
Forms of inheritance:- Forms of inheritance depends how derived classes are inheriting base class, hence it is of several form.
Class A
Class B
Class A
Class B
Class C
class C: public A, public B
{
-----------
-----------
};
Class A
class B: public A
Class C
Class B
Class D
class D: public A
{
-----------
-----------
};
Class A
Class B
Class C
class C: public B
{ Single Inheritance
-----------
-----------
};
Class A
Class B
Class C
Class D
Abstraction:- To model any real life object in OOPS, an “object†has to be instantiated from a specific “classâ€. This basic process of forming a class is known as abstraction.
In C++, classes are used to categorize data in order to model real life systems. Abstraction is this process of categorizing data.
Messages:- Software objects interact and communicate with each other sending messages to each other. When object “A†wants object “B†to perform one of its methods, object “A†sends a message to object “Bâ€.
Sometimes the receiving object needs more information so that it knows exactly, what to do then this information is passed along with the message as parameters.
message
message with parameter
Binding:- The linkage between a function call and a function definition is often referred to as binding. A linker acts as a form of binding mechanism, but most linkers support only a restricted type of binding, i.e. compile-time binding.
The main issue about binding is whether it is resolved at the time the program is compiled, or at the time the program is run hence there are two types of binding.
Static or Early or Compile Time binding:- When binding resolved at compile time it is said to be a Static or Early or Compile Time binding. Most structured programming languages do not make any distinction between the two types of binding because all binding is resolved at compile time.
During compilation the compiler creates object files. The linker takes object files and libraries and arranges them in a particular order creating an executable file. while compilation is being done, some function calls and data references in a particular object file will be unresolved.
Dynamic or Late or Run Time binding:- When binding resolved at runtime it is said to be a Dynamic or Late or Run Time binding. In other word, the ability to delay function resolution until run time is called late binding. Late binding is an essential feature of an object-oriented programming language because it is the mechanism that implements polymorphism.
Dynamic binding eliminates the need for any one component to have an overall structural knowledge of a class hierarchy.
By declaring methods as virtual function is called using a pointer or reference to an object. Dynamic binding is not used if we call a virtual function using the object itself.
Tokens:- In a C and C++ program the smallest individual units are known as C tokens. C and C++ has six types of tokens i.e. Keywords, Identifiers, Constants, String, Special Symbols and Operators.
float, while +, -, * %
name, age -18.5, 80 “ABCâ€, “Pkumar†[ ], { }
Constructor:- A constructor is also a type of member function having same name as class-name and it does not return a value, or even void. A constructor is called automatically at the moment an object is created. The purpose of a constructor is to set the initial state (value) of an object.
If the implementer does not define a constructor in a class then the compiler creates a default constructor. A default constructor is a constructor that takes no arguments. A class can have several constructors.
Destructors:- A destructor is also a type of member function having same name as class-name and is prefixed by a tilde (~) prefix. It does not return a value, or even void. A destructor is called automatically at the moment an object of the class is destroyed or object goes out of scope.
If the implementer does not define a destructor in a class then the compiler provides a default destructor. A default destructor is a destructor that takes no arguments. Every class has exactly one destructor.
Example of constructor and destructor.
#include<iostream.h>
class Abc
{
public:
int x,y,z;
private:
Abc() //defining constructor
{
x=10;
y=15;
cout<< “Constructor calledâ€;
}
~Abc() //defining destructor
{
cout<<“Destructor calledâ€;
}
void sum() //defining member function
{
z=x+y;
cout<<â€Sum is “<<z;
}
}
void main()
{
Abc a; //creating object of class Abc
a.sum(); //calling member function with the help of object
}
Templates:- If a class is framework around a data type, supporting various operations on the type. Then the data type is isolated from the class, allowing the class to deal with a generic data type. This parameterized class is actually a description of a class and is called a class template. This template is then used by the compiler to create a real class at compilation time, using a specific type.
Templates enable you to define generic classes and generic functions.A class template specifies how individual classes can be constructed much as a class declaration specifies, how individual objects can be constructed. A function template defines a family of functions.
It is a simple process to create a generic class using a template with an anonymous type. The general formate of a class template is:-
template<class T>
class class_name
{
//class member specification with anonymous type T
//where appropriate
};
Function templates ate defined like simple function, but prefixed with the keyword template along with some parameters. Function template are defined as follows:-
template<class T>
void function_name(T varname,…..)
{
-------------
-------------
}
Advantage of Templates:- Templates helps you define classes that are general in nature (generic classes). With class templates, you can eliminate the need for any type casts and define parameterized class in a safe manner.
Example of template class:-
#include<iostream.h>
#include<conio.h>
template<class T> //declaration of class template
class array
{
int s;
T *arr; //creating template type pointer
public:
array(int len)
{
arr=new T[len]; //allocating memory to pointer
s=len;
}
void input(char *p)
{
cout<<"Enter "<<p<<" type value in arrayn";
for(int i=0;i<s;i++)
{
cin>>arr[i];
}
}
void disp()
{
for(int i=0;i<s;i++)
{
cout<<arr[i]<<" ";
}
}
};
void main()
{
array<char> a(5); //creating template type object
a.input("char");
a.disp();
array<int> b(5); //creating template type object
a.input("int");
a.disp();
array<float> c(5); //creating template type object
a.input("float");
a.disp();
getch();
}
Example of function template:-
#include<iostream.h>
#include<conio.h>
template<class T>
void swap(T &x, T &y)
{
T tp=x;
x=y;
y=tp;
}
void main()
{
int i=0,j=2;
clrscr();
swap(i,j);
cout<<i<<" "<<j<<endl;
char a='A',b='B';
swap(a,b);
cout<<a<<" "<<b;
getch();
}
File handling:- As we know that file handling means writing streams to file or reading streams from file. C++ I/O occurs in streams of bytes. A stream is simply a sequence of bytes. In input operations, the bytes flow from a device to main memory. In output operations, bytes flow from the main memory to a device. The
C++ iostream library provides hundreds of I/O capabilities. C++ programs include the <iostream.h> header file, which contains the basic information required for all stream I/O operations. This header file contains the cin, cout, cerr etc. objects which correspond to the standard input stream, standard output stream, the unbuffered standard error stream, and buffered standard error stream.
Classes which are mostly used for file I/O are ifstream for input files, ostream for output files and fstream for files that will be used for both input and output. These classes are derived from istream, ostream and iostream. The class hierarchy of these file is as follow:-
#include<fstream.h>
void main()
{
char str[80];
cout<<â€Enter any String :â€;
cin>>str;
ofstream put(“abc.txtâ€); //create a file for output
put<<str;
}
#include<fstream.h>
void main()
{
char str[80];
ifstream get(“abc.txtâ€);
whil(get)
{
get.getline(str,80);
cout<<str;
}
}
#include<fstream.h>
class student
{
char name[20];
int roll;
public:
void input()
{
cout<<â€Enter name : “; cin<<name;
cout<<â€Enter Roll : “; cin<<roll;
}
};
void main()
{
student stu;
stu.input();
ofstream out(“student.datâ€);
out.write((char *) &stu, sizeof(stu));
}
Reading an object from disk:-
#include<fstream.h>
class student
{
char name[20];
int roll;
public:
void disp()
{
cout<<â€Your name is : “<<name;
cout<<â€Roll No. : “<<roll;
}
};
void main()
{
student stu;
ifstream get(“student.datâ€);
get.read((char *) &stu, sizeof(stu));
stu.disp();
}
Exception Handling:- Exception refer to unusual conditions in a program. They are usually run-time program anomalies such as division by zero, arithmetic or array overflow, and exhaustion of free store. They can be outright errors that cause the program to fail or conditions that can lead to errors.
Exception handling allows one section of a program to sense and dispatch error conditions, and another section to handle them.
To perform exception handling, our program use the try and catch keyword.
Example:-
#define toobig 1000
#define toosmall 1
#include<iostream.h>
int div(int x, int y)
{
if(y==0)
{
throw “Division by zeroâ€;
}
if((x>toobig && y>toobig) || (x<toosmall && y<toosmall))
{
throw “Overflow errorâ€;
}
return x/y;
}
void main()
{
int r;
try
{
r=div(100,10);
cout<<â€nResult is “<<r;
r=div(100,0);
cout<<â€nResult is “<<r;
}
catch(char *p)
{
cout<<p<<endl;
}
}