Storage_class struct user_defined_name
{
datatype1 member1;
datatype2 member2;
.......... .............
......... .............
};
above declaration is the general format of a simple structure declaration in C.
where Storage_class refers to the scope of stucture variable it may automatic,resister,static or external.
struct is a keyword which shows the start of a structure.
user_defined_name is structure name defined by the user.
structure is a collection hetrogenous(different) type of data.structure declaration forms a template that
may be used to create structure objects(i.e instances of a structure).
once the structure type has been defined,we can create variables of that type usingdeclarations that are similar to the built-in type
declarations.
e.g
strucrt home
{
char name[10];
int age;
float income;
} father,mother,son,daughter;
OR
struct home father,mother,son,daughter;
where father ,mother,son,daughter are sturcture variables.
member variables(name,age,income) can be accessed by using dot or period operator as follows:
strcpy(father.name,"OM");/* or father.name="OM";*/
father.age=49;
father.income=15625.750;
strcpy(son.name,"Krishna");
son.age=21;
son.income=659.41;
limitations of C structure:
Ø C does not allow the struct data type to be treated like built-in types.
e.g
struct home
{
float a;
float b;
}s1,s2,s3;
ü s1,s2,s3 can easily be assigned values using the dot operator,
but can not be added or subtracted one from other as:
s3=s1+s2;
is illegal in C.
Ø Another important limitation of C structures is that they do not permit data hiding .
ü Structure members can be directly accessed by structure variables by any function anywhere in their scope i.e structure members are public members.
Extensions to Structures:-
In C++ we expended C structure as
ü C++ structure can have both variables and functions as members.
ü C++ structure can also declare some of its members as ‘private’, ’public’ or protected.
ü The keyword strucrt can be omitted in the declaration of structure variables. e.g we can declare home variable father as:
home father; //this is valid in C++ and make an error in C
ü C++ expended structure capabilities to suit OOP philosophy (abstraction, encapsulation, polymorphism, inheritance )
C++ incorporates all above extensions in another user-defined type known as class.
Most of C++ programmers tend to use the structure for holding data type,and classes to hold both data and functions.
The only difference between a structure and a class in c++ is that,
· By default,the members of a class are private.
· By default ,the members of a structure are public.
In Java the concept of structure is totally eliminated and the concept of class is implemented , also some modifications in the concept of class have done.
Tweet
Tweet