Class and object creation in cpp

For the more Basic details about class and object of OOP go to this link
What is object oriented programming language

After reading above article i think you got the basic idea about class and object ,here now you will know how we create class and object in cpp

A basic program to understand these terms

#include<iostream>

using namespace std;

class basic

{

  int  length,width ;        // variable of class. 

   public: //described below,what mean of public is.  
  int  make_rect()        // function of class 
    {  
      cout<<"Enter the length of rectangle ";

        cin>>length;

      cout<<"Enter the width of rectangle "; 

        cin>>width;

     return length*width ;
   }
};

int main()
  {      

     int  result;
      basic b ;        // creating an object 

   // calling the function make_rect() of class basic 
       result=b.make_rect();
 
      cout<<"The rectangle area is "<<result;
  }


Now understand the program line by line

first we make class named "basic " and it has threee member
two variable and one function
function is using both variable and returning their multiplication .

  public: 

    This keyword is given just before the function make_rect().This is called access specifier.
                                       use of this is to make the function public i.e. this function can be accessible from outside the class .
                                           By default  the member of a class in cpp is private so variable "lenght,width " are private and no problem becouse these variable is using inside the class but the" function make_rect()" is using in main i.e. outside the class so we must have to make it public

That's why keyword public is given .

For know more about access specifier click below link 

what-is-access-specifier-in-cpp

now in main,
Basic b means we are creating the object of class "basic". because we can access member of a class using only object and we can two or more object of a class .

 b.make_fun();

that means we are accessing the function make_fun() of object b that is of class basic .

if we declare the variable as public in class then this will be also a valid statement and we can access the variable also from out side the class .

this program will illustrate this

      

#include<iostream>

using namespace std;
class basic
  {  
     public:  
      int  length,width ;  // variable of class basic.
    int  make_rect()       // function of class basic. 
      {           
         return length*width ;

      }
  };

int main()
 {      
    int  result;
       basic b ;  // creating an object 

      cout<<"Enter the length of rectangle ";
          cin>>b.length;

      cout<<"Enter the width of rectangle "; 
            cin>>b.width;

    // calling the function make_rect() of class basic 
          result=b.make_rect(); 

     cout<<"The rectangle area is "<<result;

 }


    

Share on Google Plus

0 comments: