class
User defined data type as like build in type, user create it based on own need.
Object oriented programming (OOP) has four pillar:
- Abstraction
- Encapsulation
- polymorphism
- Inheritance
Abstraction: Hide the internal detail and expose only required things. Example: Stack API. Here client is using API but does not know about internal data structure whether linked list or array have been used.
Encapsulation: Binding needed data member and member function in one unit that is class, make data members as private (data hiding) and they should be accessed by member functions.
polymorphism: Poly means “many” and morphism means “quality or state of having (such) a form”. One thing has many form. They look like same but internally different. There are 2 type:
- compile type: Function overloading and operator overloading.
- run time type: (Function overriding) using virtual we achieve this (Base class and derived class has SAME function but both have different purpose).
Inheritance: It same like person inheriting the property from parent. There are 3 benefits:
- Use the function/s from Base class so no need to write again.
- In Derived class we can write our new functions.
- In derived class we overload function and can achieve new functionality.
Abstract class
Class contains one or more pure virtual function then we call it “Abstract class”.
Key Points:
- We cannot create object of abstract class.
- We can create pointer of abstract class.
- Mainly it is used as base class in inheritance hierarchy.
- Main objective of abstract class is force the derived class to implement pure virtual function.
- If derive class does not implement the pure virtual function then derive class will also become abstract class.
Interface
If Class having all functions are pure virtual functions then we call it “Interface”.
Source code of shared mutex with shared lock c++:
#include<iostream> #include<fstream> #include<memory> class image { public: void display() { std::cout<<"Displaying"<<std::endl; } virtual int open()=0; }; class png: public image { int open() { std::cout<<"opening and parsing png"<<std::endl; return 0; } }; class jpg: public image { int open() { std::cout<<"opening and parsing jpg"<<std::endl; return 0; } }; int main() { std::cout<<"In main"<<std::endl; std::cout<<"Select image type 1 for png and 2 for jpg"<<std::endl; int type = 0; std::cin>>type; std::unique_ptr<image>ptr = nullptr; switch(type) { case 1: { std::cout<<"Its png"<<std::endl; ptr.reset(new png); ptr->open(); ptr->display(); break; } case 2: { std::cout<<"Its jpg"<<std::endl; ptr.reset(new jpg); ptr->open(); ptr->display(); break; } default: std::cout<<"Wrong input"<<std::endl; break; } return 0; }