Thursday 25 July 2013

Difference between classes and structures in c++.

Simple but many(or few) people misunderstood or are a not aware ability of structure in cpp to hold both member functions and data members.
                In C++, structure can have both variables and functions as members.It can also declare some of its members as 'private' so that they cannot be accessed directly by the external functions.Since class is a specially introduced data type in C++, most of programmers use the structures for holding only data, and classes to hold both the data and the functions.The only difference between a structure and a class is that structure members have public access by default and class members have private access by default, you can use the keywords class or struct to define equivalent classes.

Example:


struct employee
{
private:      //c++ structures can have access labels
int emp_no;
protected:
float salary;
public:
void getdata()   //c++ sturctures can hold both member functions and data members
{
cin>>emp_no>>salary;
}
void putdata()
{
cout<<emp_no<<salary;
}
}object1;
void main()
{
object1.getdata();
object1.putdata();
}

External Links:

http://en.wikibooks.org/wiki/C%2B%2B_Programming/Structures

http://en.wikipedia.org/wiki/C%2B%2B_classes 

0 comments:

Post a Comment