Wednesday 16 April 2014

Difference between structure and class in c++

If you don't specify public: or private:, members of a struct are public by default; members of a class are private by default.

I'm sure there are other differences to be found in the obscure corners of the C++ specifications.

In absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class.

Member of a class defined with the keyword class are private by default. Members of a class defined with the keywords struct or union are public by default.

Syntax of Structure:-
  
struct Books{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
}book; 
 
Here Structure Name is Books and variable is title, author, subject and book_id.
the optional field object_names can be used to directly declare objects of the structure type.
For example, the structure objects book. 

The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional.

Syntax of Class:-
A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the keyword class.

class Box {
   public:
      double length;   // Length of a box
      double breadth;  // Breadth of a box
      double height;   // Height of a box
};

The keyword public determines the access attributes of the members of the class that follow it. A public member can be accessed from outside the class anywhere within the scope of the class object. You can also specify the members of a class as private or protected.

 

1 comment: