Beware while using Classes

I wanted to write this section to illustrate the most important concept of classes. I think after reading this section you will be quite clear about classes. A few points to remember while using classes are : 

You cannot access private members of a class directly.

Private members can only be accessed through the member functions (which have to be public).

An object can directly call only public functions. Private ones cannot be accessed directly.

I'll make the concept clear with an example.

class add
{
private :
            int num1, num2, num3;                                
// The member data has been made private
public : 
        void input (int var1, int var2) 
            {
                num1 = var1;
                num2 = var2; 
            }
// ... you could have other member functions
}; 
int main ( )
{
    add a1;                                                                         
// Creating an object a1
    cout<<"Enter a value for num1";
    cin>>a1.num1;                                                  
  // *** Error cannot run this program ***
    return 0;
}

The program will not run because of the code : a1.num1;
a1 is an object of the class add. num1 is a private member of class add. Private members cannot be accessed directly by the object. Therefore, a1.num1 is an error. You can access num1 only through one of you public functions.

Learn about : Constructors

or go back to the : Contents section