Code About Us Tutorial


  Basic Classes
    What is a Class?
    Class Functions
    Creating Class Objects
    Constructors
    Destructors


   
 

Home > Basic Classes > Creating Class Objects

November 29, 2009 5:17 pm

   

Creating Class Objects

Now that we know how to create a class, we will put the class to use and create an object from the class. Here is an example using the above class.

 

 
#include <iostream.h>
#include "employee.h"

int main() { cout <<"Creating Employee....nn"; Employee Cory; cout<<"Setting age of Employee....nn"; Cory.setAge(16); cout <<"Getting Employee's agenn"; cout <<"Employee Age: " << Cory.getAge() << "nn";

return 0; }

First we have to include the separate file so it can access the class, this is achieved by inserting the keyword #include and then by typing the name of the separate file. Don’t forget the “ “ and the .h extension. To create an object all you have to do is to type the name of the class, in this example it will be Employee, then you type the name of the new object you wish to create. I created an Employee object named Cory.

 

 
Employee Cory;

Now if you want to access the Object(Cory)’s member functions, use a dot ‘.’ Then the name of the member function for instance:

 

 
Cory.setAge(16);

This called Cory’s member function setAge(); Now Cory has an age of 16. We want to print out Cory’s Age so we have to call the getAge() function.

 

 
Cory.getAge();

This retrieves the age and prints it to the screen. I hope that sums up how to create objects and access the member functions of the class. Please Rate this Code:


    Comments for: Creating Class Objects
Annonymouse User says:
something about creating arrays of classes might be useful.




Add Comment:
Name:
Email:


 «