Class-Object Definition

When you define a class, you substantially create a new type consisting of data and functions that, in most cases, operate on such data. By definition, all data and functions are not accessible outside the class, unless the keyword public (or protected) precedes them. By typing:
class intClass
{
     int a;
public:
     void seta(int x)    
     {
           a = x;    
     }
};
a new type is created, which consists of an entity comprising a variable a and a function seta(). After the class has been defined, objects of its type can be declared:
intClass anObject;
anObject contains a variable a which can be set through the function seta():
anObject.seta(12);
seta() can be called outside the class because it is a public member function. The variable a, though, is not accessible from outside the class, as it is private, which is the default condition for all members of a class.

Example


#include <iostream>
using namespace std;

// create a new class
class intClass
{
     int a;    // by definition all members of a class are
               // private: not accessible from outside the class
public:
     void seta(int x) // members preceded by public: can be
                      // accessed from the outside
     {
           a = x;  // a, although private, can be accessed by
                   // seta() because seta() is a member of intClass  
     }
};

int main()
{
    intClass obj1; // declares an object of type intClass
    intClass obj2;
    obj1.seta(34); // the function seta() can be called because
                   // it is public
                   // obj1.a = 34; would fail, because a is private
    obj2 = obj1;   // an object can be assigned to another of the
                   // same class. The result is that
                   // all data gets copied from obj1 to obj2
}