class keyword


The concept of a class allows you to encapsulate a set of related variables and only allow access to them via predetermined functions.

The class keyword is used to declare the group of variables and functions and the visability of the variables and functions. Here is a basic example.


    class String 
    {
    public:
  
        void Set(char *InputStr)   // Declare an Access function
        { 
            strcpy(Str, InputStr); 
        }

    private:
        
        char Str[80];      // Declare a hidden variable.
  
    };

Now we have declared a class called String we need to use it.


    main()
    {
        String Title;
        
        Title.Set("My First Masterpiece.");
    }

This code creates a String object called Title and then uses the Set member function to initialise the value of Str.

In C++ the member function Set is also known as a method

This is the strength of object oriented programming, the ONLY way to change Str is via the Set method.

The final code example brings the last two examples together ands a new method (called Get) that shows the contents of Str


    #include <stdlib.h>
    #include <iostream.h>               // Instead of stdio.h

    class String 
    {
    public:
  
        void Set(char *InputStr)   // Declare an Access function
        { 
            strcpy(Str, InputStr); 
        }
        
    char *Get(void)                // Declare an Access function
        { 
            return(Str); 
        }
        

    private:
        
        char Str[80];      // Declare a hidden variable.
  
    };

    main()
    {
        String Title;
        
        Title.Set("My First Masterpiece.");
        
        cout << Title.Get() << endl;
    }


Examples:

Example program.

See Also:

Constructors and destructors.

Class Inheritance.


C References


Top Master Index C++ Keywords Functions


Martin Leslie 08-Feb-96