* * *

What is OOPs ?

Object-oriented programming (OOP) is nothing but that which allows the writing of programs with the help of certain classes and real-time objects. We can say that this approach is very close to the real-world and its applications because the state and behaviour of these classes and objects are almost the same as real-world objects.

Object Oriented Programming is a paradigm that provides many concepts such as inheritance, data binding, polymorphism etc.

The programming paradigm where everything is represented as an object is known as truly object-oriented programming language.

 

Why and How OOPs comes into picture ?

At the beginning of the computing era, programming was usually limited to machine language programming. Machine language means those sets of instructions that are specific to a particular machine or processor, which are in the form of 0’s and 1’s. These are sequences of bits (0100110…). But it’s quite difficult to write a program or develop software in machine language.

It’s actually impossible to develop software used in today’s scenarios with sequences of bits. This was the main reason programmers moved on to the next generation of programming languages, developing assembly languages, which were near enough to the English language to easily understand. These assembly languages were used in microprocessors. With the invention of the microprocessor, assembly languages flourished and ruled over the industry, but it was not enough. Again, programmers came up with something new, i.e., structured and procedural programming.

Structured Programming


The basic principle of the structured programming approach is to divide a program into functions and modules. The use of modules and functions makes the program more understandable and readable. It helps to write cleaner code and to maintain control over the functions and modules. This approach gives importance to functions rather than data. It focuses on the development of large software applications, for example, C was used for modern operating system development. The programming languages: PASCAL (introduced by Niklaus Wirth) and C (introduced by Dennis Ritchie) follow this approach.

Procedural Programming Approach


This approach is also known as the top-down approach. In this approach, a program is divided into functions that perform specific tasks. This approach is mainly used for medium-sized applications. Data is global, and all the functions can access global data. The basic drawback of the procedural programming approach is that data is not secured because data is global and can be accessed by any function. Program control flow is achieved through function calls and goto statements. The programming languages: FORTRAN (developed by IBM) and COBOL (developed by Dr Grace Murray Hopper) follow this approach.

There were still some issues with these languages, though they fulfilled the criteria of well-structured programs, software etc. They were not as structured as the requirements were at that time. They seem to be over-generalised and don’t correlate with real-time applications.

To solve such kinds of problems, OOP, an object-oriented approach was developed as a solution.

The Object-Oriented Programming (OOP) Approach

The OOP concept was basically designed to overcome the drawback of the above programming methodologies, which were not so close to real-world applications. The demand was increased, but still, conventional methods were used. With the emergence of OOP, all conventional methods were thrown out the window. OOP methodology not only solved the modern-era problem, but also, it brought a revolution in the programming methodology field.

 

What is Object ?

Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It can be physical and logical. The objects can contain both data as well as functions. It simplifies the software development and maintenance by providing some concepts:

  

  • Object

  • Class

  • Inheritance

  • Polymorphism

  • Abstraction

  • Encapsulation

What is Class ?

Collection of objects is called class. It is a logical entity.

It is the basic concept of OOP; an extended concept of the structure used in C. It is an abstract and user-defined data type. It consists of several variables and functions. The primary purpose of the class is to store data and information. The members of a class define the behaviour of the class. A class is the blueprint of the object, but also, we can say the implementation of the class is the object. The class is not visible to the world, but the object is.

Access Specifiers >

Public - The members declared as Public are accessible from outside the Class through an object of the class.

Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.

Private - These members are only accessible from within the class. No outside Access is allowed.

By deafult class members are private.

A example of class :

    #include  
    using namespace std;  
    class Employee {  
       public:  
           int id;   
           string name;  
           float salary;  
           void insert(int i, string n, float s)    
            {    
                id = i;    
                name = n;    
                salary = s;  
            }    
           void display()    
            {    
                cout<     };  
    int main(void) {  
        Employee e1;   
        Employee e2;  
        e1.insert(201, "Sonoo",990000);    
        e2.insert(202, "Nakul", 29000);    
        e1.display();    
        e2.display();    
        return 0;  
    }  

 

What is Inheritance ?

When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability whenever possible and reduce its redundancy.

Example of Inheritance :

#include  
using namespace std;
 
class Box {
   protected:
      double width;
};
 
class SmallBox:Box { 
   public:
      void setSmallWidth( double wid );
      double getSmallWidth( void );
};
 
double SmallBox::getSmallWidth(void) {
   return width ;
}
 
void SmallBox::setSmallWidth( double wid ) {
   width = wid;
}
 
int main() {
   SmallBox box;
   box.setSmallWidth(5.0);
   cout << "Width of box : "<< box.getSmallWidth() << endl;
 
   return 0;
}

  1. A derived class with only one base class is called single inheritance.

  2. A derived class with multiple base class is called multiple inheritance.

  3. Multiple derived classes with same base class is called hierarchical inheritance.

  4. A derived class with one base class and that base class is a derived class of another is called multilevel inheritance.

  5. Combination of multiple and hierarchical inheritance is called hybrid inheritance.

What is Polymorphism ?

Polymorphism means “Poly mean Multiple” + “Morph means Forms” .

Polymorphism is the ability for data to be processed in more than one form. It allows the performance of the same task in various ways.

 

1. Compile time polymorphism: In Compile time Polymorphism, call is resolved by the compiler. This type of polymorphism is achieved by function overloading or operator overloading. 

Function Overloading --

You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type.

#include  
using namespace std;

class printData {
   public:
      void print(int i) {
        cout << "Printing int: " << i << endl;
      }
      void print(double  f) {
        cout << "Printing float: " << f << endl;
      }
      void print(char* c) {
        cout << "Printing character: " << c << endl;
      }
};

int main(void) {
   printData pd;

   // Call print to print integer
   pd.print(5);

   // Call print to print float
   pd.print(500.263);

   // Call print to print character
   pd.print("Hello C++");

   return 0;
}

Operator Overloading --

Overloaded operators are functions with special names: the keyword "operator" followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.

#include  

using namespace std;

class box{
    int l,b,h;
    public:
        box(int a=2,int f=2,int c=2)
        {
            l=a;
            b=f;
            h=c;
        }
        box operator +(box& a)
        {
            box z;
            z.l=this->l+a.l;
            z.b=this->b+a.b;
            z.h=this->h+a.h;
            return z;
        }
        int get(void)
        {
            return l*b*h;
        }
};

int main()
{
    box a1(6,7,5),a2(12,13,10),a3;
    a3=a1+a2;
    int volume=a3.get();
    cout< }

2. Run time polymorphism: In Run time Polymorphism, call is not resolved by the compiler. This type of polymorphism is achieved by virtual functions. 

Virtual Functions --

A virtual function a member function which is declared within base class and is re-defined (Overriden) by derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.

#include  

using namespace std;

class base{
    public:
        virtual void print()
        {
            cout<<"print base class"<         }
        void show()
        {
            cout<<"show base class"<         }
};

class derived:public base
{
    public:
        void print ()
        {
            cout<<"print derived class"<         }
        void show()
        {
            cout<<"show derived class"<         }
};

int main()
{
    base *a;
    derived b;
    a=&b;
    a->print();
    a->show();
}

What is Abstraction ?

Abstraction refers to the act of representing important and special features without including the background details or explanation about that feature. Data abstraction simplifies database design.

  1. Physical Level:
    It describes how the records are stored, which are often hidden from the user. It can be described with the phrase, “block of storage.”

  2. Logical Level:
    It describes data stored in the database and the relationships between the data. The programmers generally work at this level as they are aware of the functions needed to maintain the relationships between the data.

  3. View Level:
    Application programs hide details of data types and information for security purposes. This level is generally implemented with the help of GUI, and details that are meant for the user are shown.

Example :

#include  
using namespace std;

class adder{
    public:
        adder(int i=0){
        total=i;}
        void addnum(int num){
        total+=num;}
        int gettotal(){
        return total;}
    private:
        int total;
};

int main()
{
    adder a;
    a.addnum(10);
    a.addnum(20);
    a.addnum(30);
    cout<<"Total ";

     return 0;
}

What is Encapsulation ?

Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines.

 

Example :

#include  
 
using namespace std;
 
class Box {
   public:
      double length;
      void setWidth( double wid );
      double getWidth( void );
 
   private:
      double width;
};
 
double Box::getWidth(void) {
   return width ;
}
 
void Box::setWidth( double wid ) {
   width = wid;
}
 
int main() {
   Box box;
   box.length = 10.0;
   cout << "Length of box : " << box.length ;     box.setWidth(10.0); 
   cout << "Width of box : " << box.getWidth() ; 
   return 0;
}

Friend Funtions

A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.

A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends.

To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend as follows −

#include
using namespace std;
 
class Box {
       double width;
   
   public:
      friend void printWidth( Box box );
      void setWidth( double wid );
};

void Box::setWidth( double wid ) {
   width = wid;
}

void printWidth( Box box ) {
   cout << "Width of box : " << box.width < }
 
int main() {
   Box box;
   box.setWidth(10.0);
   printWidth( box );
   return 0;
}

THIS pointer

Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object.

Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer.

#include
using namespace std;

class Box {
   public:
      Box(double l = 2.0, double b = 2.0, double h = 2.0) {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
      }
      double Volume() {
         return length * breadth * height;
      }
      int compare(Box box) {
         return this->Volume() > box.Volume();
      }
      
   private:
      double length;    
      double breadth;   
      double height;    
};

int main(void) {
   Box Box1(3.3, 1.2, 1.5);    
   Box Box2(8.5, 6.0, 2.0);    

   if(Box1.compare(Box2)) {
      cout << "Box2 is smaller than Box1" <    } else {
      cout << "Box2 is equal to or larger than Box1" <    }
   
   return 0;
}

The Class Constructor

A class constructor is a special member function of a class that is executed whenever we create new objects of that class.

A constructor will have exact same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables.

#include
using namespace std;
class Employee {
   public:
       int id;
       string name;
       float salary;
       Employee(int i, string n, float s)  
        {  
            id = i;  
            name = n;  
            salary = s;
        }  
       void display()  
        {  
            cout<         }  
};
int main(void) {
    Employee e1 =Employee(101, "Sonoo", 890000); 
    Employee e2=Employee(102, "Nakul", 59000); 
    e1.display();  
    e2.display();  
    return 0;

The Class Destructor

destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class.

A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc.

#include  
    using namespace std;  
    class Employee  
     {  
       public:  
            Employee()    
            {    
                cout<<"Constructor Invoked"<             }    
            ~Employee()    
            {    
                cout<<"Destructor Invoked"<             }  
    };  
    int main(void)   
    {  
        Employee e1;
        Employee e2; 
        return 0;  
    } 

Templates

Templates are powerful features of C++ which allows you to write generic programs. In simple terms, you can create a single function or a class to work with different data types using templates.

Templates are often used in larger codebase for the purpose of code reusability and flexibility of the programs.

The concept of templates can be used in two different ways:

  • Function Templates

  • Class Templates

Function Templates

A function template works in a similar to a normal function, with one key difference. A single function template can work with different data types at once but, a single normal function can only work with one set of data types.

Normally, if you need to perform identical operations on two or more types of data, you use function overloading to create two functions with the required function declaration.

However, a better approach would be to use function templates because you can perform the same task writing less and maintainable code.

#include
using namespace std;

template
T large(T n1,T n2)
{
    return (n1>n2)?n1:n2;
}

int main()
{
    char i1,i2;
    cin>>i1>>i2;
    cout< }

Class Templates

Like function templates, you can also create class templates for generic class operations. Sometimes, you need a class implementation that is same for all classes, only the data types used are different.

Normally, you would need to create a different class for each data type OR create different member variables and functions within a single class. However, class templates make it easy to reuse the same code for all data types.

#include
using namespace std;

template
class add{
    T num1,num2;
    public:
        add(T n1,T n2)
        {
            num1=n1;
            num2=n2;
            cout<         }
};
int main()
{
    add a1(50,100);
    return 0;
}

  • A separate library called STL (Standard Template Library) for C++ users is available which will provide you a many containers and data structures on the tip of your hand. It will also helps you in competitive coding.

           --Learn STL from GeeksforGeeks --