Code Library
Home Submit Free Hosting Link To Us Contacts

CPP Classes

CPP Classes CPP CPP Classes Download (.zip)



#include <iostream.h>

class computer //Standard way of defining the class
{
 private: //This means that all the variables under this, until a new type of restriction is                         
                   //placed, will only be accessible to functions that are part of this class.
 //NOTE: That is a colon, NOT a semicolon...
 int processorspeed;
 
 public: //This means that all of the functions below this(and variables, if there were any)                  
                  //are accessible to the rest of the program.
 //NOTE: That is a colon, NOT a semicolon...
 void setspeed(int p); //These two functions will be defined outside the class
 
 int readspeed(); 
};                                           //Don't forget the trailing semi-colon

void computer::setspeed(int p) //To define a function outside put the name of the function 
                                                           //after the return type and then two colons, and then the name 
                                                           //of the function. 
{
  processorspeed = p;
}
int computer::readspeed()  //The two colons simply tell the compiler that the function is part 
                                                   //of the class
{
  return processorspeed;
}

void main()
{
  computer compute;  //To create an 'instance' of the function, simply treat it like you would                         
                                           //a structure.  (An instance is simply when you create an actual object 
                                         //from the class, as opposed to having the definition of the class)
  compute.setspeed(100);  //To call functions in the class, you put the name of the instance,
                                                    //and then the function name.
  cout<<compute.readspeed(); //See above note.
}




  • CPPClasses


Tatet