Basics Of OOPS In C++ | Classes & Objects In C++

 Basics Of OOPS In C++ 


What is Class?

Class is like a form in programming. You know in a form you have some fields where every user fills that form. So the one form template can be filled by any user.

The class can be assumed as a generalized set of programs whereas many objects can access the features of that class.


You can understand class by this image easily:- 


Here in this example, you can see a template of a car that can be accessed by many car companies like polo, mini, beetle etc.

So here polo, mini, beetle are called objects which is an instance (user) of car class.
A class may have data members (attributes) and methods (functions) like the structures you can understand this concept by this image - 


So here car class has methods and attributes so the objects of this class should have access to these methods and attributes.

Access Specifier In OOPS C++ - 

  • public - members are accessible from outside the class
  • private - members cannot be accessed (or viewed) from outside the class
  • protected - members cannot be accessed from outside the class, however, they can be accessed in inherited classes. You will learn more about Inheritance later.
By default all the data members and methods are private in a class.




How to Create Class In  C++ - 

//If You are not able to see
//complete code then
//just rotate your smartphone

#include <iostream> //HEADER FILE
using namespace std;

class Car
//Syntax class className
{
    int model_no; //private

    public:
    int maxspeed; //public 
    int fuelTank_Cap; //public

    private:
    void setSpeed(); //private

    public:
    void getFuel(); //Public
};


int main()
{
    return 0;
}






How to access data members or methods of a class by an object in C++?


#include <iostream> //HEADER FILE
using namespace std;

class Car
//Syntax class className
{
    int model_no; //private

    public:
    int maxspeed; //public 
    int fuelTank_Cap; //public

    private:
    void setSpeed(); //private

    public:
    void getFuel(); //Public
};


int main()
{
    Car swift;
    cout<<"Enter The Maximum Speed Of Car"<<endl;
    cin>>swift.maxspeed; //Inserting Value Of
    // maxspeed In Swift Objects OF Car Class

    cout<<"MaxSpeed Of Swift Car is "<<swift.maxspeed<<endl;//Accessing Value Of maxspeed

    //You Can't Access Private data members and methods here
    //You can only access that in the class only

    return 0;
}


Output - 

Enter The Maximum Speed Of Car
140
MaxSpeed Of Swift Car is 140

Features Of OOPS - 

  1. Re-usability
  2. Data Redundancy
  3. Code Maintenance
  4. Security
  5. Better Productivity
  6. Polymorphism Flexibility



Comments

Popular posts from this blog

Array Of Objects In C++ | Array Of Objects Explained With Real Life Example

Pointers In C++ | Pointer Explained With Real Life Examples | Pointers In OOPs C++