Appendix D: Classes in C


Creating a class in C++ is similar to creating a structure. Class objects have members just like a structure, but instead of just data, they also have code or functions as members . The basic template is this:

  class  ClassName 
{
public:
ClassName(); // Constructor
~ClassName(); //Destructor
private:
protected:
};

The class keyword begins the definition.

The ClassName becomes the name for the class, and is used later to create instances of it.

The public keyword defines a section where the members are visible or accessible to other objects or functions.

The private keyword defines a section where the members are invisible or nonaccessible to other objects or functions. This is the default if no access type is specified. This feature helps C++ implement data abstraction.

The protected keyword defines a section where the members are like private , except that they will be visible to other classes derived from this class.

Constructor and Destructor

Inside the public section just shown, the functions ClassName and ~ClassName are defined (like in a prototype). These are the constructor and destructor for this class. The constructor is called whenever an instance of a class is created, and the destructor is called when the instance is destroyed .

Note  

The constructor and destructor are functions with the same name as the class, and have no return type. The destructor name is preceded with the tilde (~), and never accepts an argument. The constructor may be overloaded. Constructors and destructors are not required, but are most commonly implemented.

Member Functions

In order to write any member function s body, it is usually done outside the definition (the only difference between regular functions and members is the presence of ClassName:: as part of the name) in the following format:

 ClassName::MemberFunction() 
{
}

When a member function definition inside the class definition is followed by the const keyword, it means that the function will not change any of the (nonstatic) data members of that object. For instance:

 class MDate { 
public:
bool IsValid() const;
private:
int M, D, Y;
};

In the previous example, the IsValid member function of the MDate class has a const following its name and parameter list. This means that the code inside this function will not change any of the nonstatic data members, such as M, D, and Y.

Inline Functions

Inline functions can be created within the class definition, without the inline keyword. The format requires the function s body to follow the member definition:

 class Example 
{
public:
Example(); // Constructor
~Example (); // Destructor
int IsExampleEmpty( void ) { return( IsEmpty ); };
// Automatic
inline function
private:
int IsEmpty;
};



OOP Demystified
OOP Demystified
ISBN: 0072253630
EAN: 2147483647
Year: 2006
Pages: 130

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net