Home | Gaming | Programming | Play Online | Contact | Keyword Query
Games++ Games & Game Programming

GAMES++
Games++ Home
Games++ Gaming
Games++ Programming
Beta Testing Games
Free Online Games
Hints & Cheats

BROWSER UTILITIES
E-mail This Page
Add to Favorites

SITE SEARCH

Web Games++

AFFILIATES
Cheat Codes
Trickster Wiki
Game Ratings
Gameboy Cheats
PlayStation Cheats
BlackBerry Games
Photoshop Tutorials
Illustrator Tutorials
ImageReady Tutorials

ADVERTISEMENT

ADVERTISEMENT

Ch 8: Introduction to C++ Metrowerks - C++ by Metrowerks

Introduction to C++ by Metrowerks

The Fundamentals of Classes

A class defines a new data type. Or rather, redefines an old data type (the struct). These data types may then be used to create objects. An object is not only an instance of a class but may also be any type either predefined or user defined. When you create, or in C++ lingo, instantiate, a class, you create an object. Classes are declared using the keyword -- you guessed it -- class. The members of a class are always included in the class definition. Members include the data and the code that will make the class work.

Class Fundamentals

A class is a set of variables and functions that can be accessed by the other variables and functions within that class. Within a class declaration, there are usually private members and public members. Members of a class declaration are private by default, but the keyword public can be used to make members available for use by the program outside of the class in which they are declared. Private members are those that can only be accessed by other members of that class.

A class declaration is similar to the declaration of a struct. It creates a new data type. This data type can then be used to instantiate objects. Each instance of an object in a class-created data type has its own copy of the variables and functions declared by that class. The following is a declaration of a class called sample_class, which includes various variables and functions. Also, two objects of this class type are instantiated: obj1 and obj2:

class sample_class {
    int sci1;
    int sci2;
    char scch;
public:
    void scfunct1(int scparm);
    void scfunct2();
} obj1, obj2;

The dot (.) operator is required to access a variable of the class. Keep in mind that obj1 and obj2 will each have their own copies of scil, sci2, and scch. The dot operator is therefore used to tell the program which variable to access.

obj1.sci1 = 5;
obj2.sci1 += 3;
obj2.scch = 'H';

However, the above example would not work because the variables in this sample class -- scil, sci2, and scch -- are private members of the class, and cannot be accessed or changed by any external function or variable, not even the main() function.

As you can see, the things you declare within a class are similar to the things you declare for each function -- variables and function prototypes. Classes are like smaller, self-contained programs that do specialized things. You can then combine these smaller programs into bigger ones. This is the foundation of object-oriented programming.

Class Member Access

Having declared the above objects, let's look at how we would set up a function:

class sample_class {
    int sci1;
    int sci2;
    char scch;
public:
    void scfunct1(int scparm);
    void scfunct2();
} obj1, obj2;
void sample_class::scfunct1(int scparm)
{
    sci1 = scparm * 2;
    sci2 = (scparm != 0) ? (/=scparm) : scparm;
}

See the :: operator? This is called a scope resolution operator. For the example function oid sample_class::scfunct(int scparm), the scope resolution operator (::) tells the compiler that the function scfunct(int scparm) belongs to the class sample_class -- that is, it is in sample_class's scope. This is important to remember because in C++, several different classes can use the same function name. And that's okay, because the compiler knows which function belongs to which class because of the scope resolution operator!

Notice that the dot operator is not used when using the variables sci1 and sci2 within class functions. Therefore, the routines in the function will be performed on the variables associated with the object in which they are contained.

Because the two member variables are private, it is not possible for any other function to access or output the variables. Should the objects need to be output in the main() or another non-member function, a new member function will need to be declared within the class definition:

int sample_class output1();

and this function would be defined outside the definition:

int sample_class::output1()
{
    return sci1;
}

Now, if you want to output the value stored in a sample_class variable, the following code could be used:

cout << objectname.output1();

Constructors and Destructors

Before the members of a class can be used, they should be initialized, with a value. A constructor function is used for this initialization. Sometimes, when an object is destroyed, it needs to perform a final function, such as freeing up memory space that had been allocated within the object. A destructor function is used to accomplish this. The constructor function is called when the object is instantiated. The constructor function is designated by using the same name as its class and has no return type -- not even void The destructor function is declared similarly to the constructor function. However, its name is preceded by ~, the tilde character. The following sample includes the constructor and destructor functions:

class sample_class {
    int sci1;
    int sci2;
    char scch;
public:
    sample_class();    //constructor
    ~sample_class();    //destructor
    void scfunct1(int scparm);
    void scfunct2();
} obj1, obj2;

The constructor function would look like this:

sample_class::sample_class()
{
    sci1 = sci2 = 0;
    scch = 0;
}

A destructor function could look like this:

sample_class::~sample_class()
{
    cout << "Object destroyed.";
}

All classes have a constructor and a destructor. If you do not explicitly write them, the compiler will implicitly create them, though they may not initialize things the way you would like them to.

Constructors With Parameters

Like most functions, a constructor can have parameters. When an object is created, it may be necessary for the variables associated with that object to have program-specific initial values. To achieve this, you pass parameters to the constructor function when the object is being instantiated, the same way you pass parameters to a normal function.

Classes, Structures, Unions, and Inline Functions

Classes are related to both struct type and unions. We will explore these relationships here. We will then discuss another feature of C++: inline functions.

Classes and Structures

There is only one major difference between classes and structures. Although both include data and code that manipulates that data, members of a class are, by default, private and the members of a structure are, by default, public. The previous sample class declaration can be rewritten as a structure:

Important Note: In fact the terms struct and class may be interchanged within programs -- i.e., you could have class obj; in one source file and extern struct obj; in a second source file.

Why, you may ask, is there both a struct and a class type in C++? Well, structs are part of the C programming language, where there is no such thing as a private declaration. Therefore, as we made the switch from C to C++, it was necessary to retain the functionality of the struct type in a C++ program. While it is not necessary, it is a very common stylistic choice to use structs for POD (plain old data) types and use a class for a data with tightly associated methods. If you want to share your user-defined types with C programs, you will also need to use structs.

Classes and Unions

While the relationship between structures and classes is relatively evident, a more subtle relationship exists between unions and classes. Basically, a union functions like a class. However, all of its variable elements are stored in the same location. A union, like a class and a structure, can contain constructor and destructor functions. By default, members of a union are public.

Inline Functions

Frequently, class declarations contain an inline function. To increase the speed of your program, small, frequently used functions should be declared with the inline keyword.

Although inlined functions are often associated with a class, they do not have to be part of a class and often are not. In C you can write a "macro" that works like an inlined function in C++. However a macro does not have C++ type checking ability and is often limited to simple procedures.

inline int ilfunct()
{
    cout << ssi1 << " " << "\n";
}

This example of an inline function requires no parameters and it returns an integer type. However, inline functions can also accept parameters. The big advantage of using inline functions is that -- because the function is called, expanded, and completed in the same sequence -- you save memory space and retrieval time. How does this work? Simple. When you write a function that is accessible to the program as a whole, the compiler must first compile the function (along with every other non-online function), allocate memory for the function's parameters, and then assign registers pointing the variables to the function. When the function is called, the compiled function must be located (using registers) within the source code architecture, the function variables (parameters) are pushed onto the stack, the registers are invoked, and then, finally, the registers are restored when the function returns. Quite a bit of work, huh? An inline function removes these time-consuming procedures by making itself immediately available.

As an example, let's use our current code:

struct sample_struct {
    void ssfunct2();
private:
    int ssi1;
    int ssi2;
    char ssch;
} ssobj1, ssobj2;
inline int ilfunct()
{
    cout << ssi1 << " " << "\n";
}
int main()
{
    sample_struct x;
    x.ilfunct();    //use inline function ilfunct()
return 0;
}

If the compiler complies with the inline function request, then the function is expanded so that it fits into the code as if it were typed directly in as normal code. Inline functions are essentially shorthand for small pieces of code that will be used frequently. Inline functions called from objects behave as if they are part of the object.

Though a function is declared to be inline the compiler does not have to comply with the inline request. Some compilers will not generate inline code if a function contains a loop, a switch or a goto. Recursive functions will usually not be compatible with inline functions. Additionally, the use of static variables in an inline function is usually not allowed.

Note : All functions defined within a class definition are inline functions by default.

Objects and Classes

Objects can be treated in the same ways as most other data types. For example, you can create an array of objects. Objects can also be referenced by pointers and other types of data.

Pointers to Objects

Objects can be accessed directly or indirectly by a pointer, just like structs. As with a struct, the dot operator must be used when accessing an object's elements directly. What do we use when accessing an object with a pointer? Right! The arrow operator! See how this is all coming together? The following sample program shows the use of pointers with an object:

#include 
using namespace std;
class sampclass {
    int j;
public:
    void assignj(int k) {j = k;}
    void displayj();
};
void sampclass::displayj()
{
    cout << j << '\n';;
}
int main()
{
    sampclass obj[2], *p;
    obj[0].assignj(5);
    obj[1].assignj(10);
    p = obj;
    p->displayj();
    p++;
    p->displayj();
    p--;
    p->displayj();
    return 0;
}

This program uses a pointer to reference an object and an array of objects. It shows the incrementing and decrementing of a pointer. It also shows the use of the arrow and dot operators. Make sure you fully understand this program. What will the output from this program be?

5
10
5

Object References

As opposed to other data types, there are no special requirements when referencing objects. As we proceed in our discussion of classes, you will learn how referencing an object can solve certain problems relating to classes. We will discuss those situations as they arise. For now, just know that referencing an object is the same as referencing any other data type.

The this Pointer

Every member function has access to a special pointer -- this. The this pointer points back to the current object, which allows you to have member functions return their parent object. This is useful for functions such as a comparison between two objects of the same class, as seen below.

Const sampclass & sampclass::whichisbigger(const sampclass p) const {
    if (s.j > j) 
        Return s;
    else
        return *this;
}

Functions Relating to Classes

This last section of today's lesson will begin a look at how functions relate to classes. Classes are complex yet extremely important elements of your study of C++, and they deserve the attention we have given them so far. After we discuss friend functions and the overloading of constructor functions, we will look at the initialization of variables. We will then end this lesson so you can rest your brain and let everything you've learned today sink in. We will continue with functions in the next lesson.

Friend Functions

There may come a time when you have a single function that must work with two different classes of data. When this occurs, that function can be made a friend of each of those two classes. A friend function is not a member of a class, but it has access to the private parts of the class to which it has been declared a friend. A function is declared a friend of a class in the public part of the class declaration and is preceded by friend. A friend of a class can access the members of that class directly. Look at the following example:

#include 
using namespace std;
class mine {
    int m, n;
public:
    mine(int p, int q) {m = p; n = q;}
    friend int mult(mine y);
};
int mult(mine y)
{
    return y.m * y.n;
}
int main()
{
    mine z(10, 11);
    cout << mult(z);
    return 0;
}

There are several things you should notice in this program: the friend function could access the private variables directly, the creation of the object z with parameters, and the inline constructor function mine().

Next Lesson

Copyright © 1998-2007, Games++ All rights reserved. | Privacy Policy