Data Hiding

  • A key feature of object oriented programming is 'data - hiding' i.e., the data is concealed within a class, so that it cannot be accessed mistakenly by functions outside the class.
  • 'private' and 'public' are two types of protection available within a class.
  • Items marked with 'private' can only be accessed by methods defined as part of the class. Data is most often defined as private.
    Private members can be accessed by members of the class.
  • Public items can be accessed from anywhere in the program without restrictions. Class methods are usually public. As a general rule, data should not be declared public. Public members can be accessed by members and objects of the class.
  • Protected is another type of protection available within a class. Items declared as protected are private within a class and are available for private access in the derived class. The derived class concept is dealt with later in this book. The protected access will be discussed again.

  • Example:
    class fact{
    int n,fct,temp;
    public:
    void read_data()
    {
    printf("Enter the Integer whose factorial you want to find\n");
    scanf("%d", &n);
    }
    void calc_fact()
    {
    fct=1;
    temp=n;
    while (n>0)
    {
    fct=fct*n;
    n--;
    }
    printf("Factorial of %d is %d \n",temp,fct);
    }
    };
    void main()
    {
    fact f;
    clrscr();
    f.read_data();
    f.calc_fact();
    getch();
    }

    Note: As shown in the above example the variables n, fct and temp are private and can not be accessed from the main function but can be accessed from the public functions read_data() and calc_data()


    Class and Objects << Previous

    Next >> Constructors and Destructors

    Our aim is to provide information to the knowledge seekers. 


    comments powered by Disqus


    Footer1