Saturday 8 November 2014

Structure vs Class

Q. Why we use Structure or Class and when to use them ?

Ans. In the past when there was no concept of OOPS programming there was no class concept. 

Then how could we implement a real time entity (in C) and then later convert to object (in OOPS).
At that time structure was very useful to implement a real world entity in the programming. Like for example we have to make car's object or entity. Then we can use Structure name as car which can have the car's attribute. But at that time structure could not contain functions associated with the entity.

Ex.  structure definition

      Struct car {
               bool petrol;           /// It is running from petrol or diesel
               int engine_type;
               long int price;
               int capacity_seat;
               ..............etc....

};

In the above structure we map the real world car to that structure with the similar attributes what a real world car would have. But we can not define the function of the car in that structure and that is the main difference between the C structure and C++ class concept.

There is no concept of access specifier in C structure but in C++ concept of access specifier is there. A member or a member function of a class can either be public, private or protected depending upon the needs.

Ex.
            Class car{
             
             private:
               bool petrol;           /// It is running from petrol or diesel
               int engine_type;
               long int price;
               int capacity_seat;
               /////..............etc....
             public:
               // constructor which makes an object of the car
               car(int a, bool b, ////etc.....){

               }

             // destructor which destruct the object
            
             ~ car(){
                // some implementation
                  }

           } ;

In class we can define the function also. There is a concept of the constructor and destructor in oops.

Mainly differences are

                         Structure  in C                                                       Class in OOPS (C++)

1.       Do not contain function of the entity.             May contain functions of Object.

2.       No concept of access modifier.                       Member can be public , private or protected

3.       No constructor or destructor.                           Every class contains a constructor and 
                                                                                   destructor either  in 
                                                                                   built or user defined .

No comments:

Post a Comment

Related Posts

Related Posts Plugin for WordPress, Blogger...