JavaScript EditorFree JavaScript Editor     Ajax Editor 

Main Page
  Previous Section Next Section

The Scope Resolution Operator

There's a new operator in C++ called the scope resolution operator, represented by a double colon (::). It's used to make reference to class functions and data members at class scope. Don't worry too much about what that means; I'm just going to show you how to use it to define class functions outside the class.

Thus far you've been defining class member functions right inside the class definition. Although this is totally acceptable for small classes, it gets to be a little problematic for large classes. Hence, you're free to write class member functions outside the class, as long as you define them properly and let the compiler know that they're class functions and not normal file-level functions. You do this with the scope resolution operator and the following syntax:

return_type class_name::function_name(parm_list)
// function body

Of course, in the class itself, you must still define the function with a prototype (minus the scope resolution operator and class name, of course), but you can hold off on the body until later. Let's try this with your Person class and see what you get. Here's the new class with the function bodies removed:

class Person
int age;
char *address;
int salary;

// this is the default constructor

// here's our new more powerful constructor
Person(int new_age, char *new_address, int new_salary);
// here's our destructor

} ;

And here are the function bodies, which you would place with all your other functions after the class definition:

// this is the default constructor
// constructors can take a void, or any other set of parms
// but they never return anything, not even void
age     = 0;
address = NULL;
salary  = 35000;

}  // end Person


Person::Person(int new_age,
               char *new_address,
               int new_salary)
// here's our new more powerful constructor
// set the age
age = new_age;

// allocate the memory for the address and set address
address = new char[strlen(new_address)+1];
strcpy(address, new_address);

// set salary
salary = new_salary;

}  // end Person int, char *, int


// here's our destructor
}  // end ~Person


Most programmers place a capital C before class names. I usually do, but I didn't want to trip you out. Thus, if I was programming, I probably would have called it CPerson instead of Person. Or maybe, CPERSON in all caps.

      Previous Section Next Section

    JavaScript EditorAjax Editor     JavaScript Editor