class keyword in C++

By: Charles Emailed: 1787 times Printed: 2615 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Syntax for the class keyword is as follows.

class class_name
// access control keywords here
// class variables and methods declared here

You use the class keyword to declare new types. A class is a collection of class member data, which are variables of various types, including other classes. The class also contains class functions--or methods--which are functions used to manipulate the data in the class and to perform other services for the class. You define objects of the new type in much the same way in which you define any variable. State the type (class) and then the variable name (the object). You access the class members and functions by using the dot (.) operator. You use access control keywords to declare sections of the class as public or private. The default for access control is private. Each keyword changes the access control from that point on to the end of the class or until the next access control keyword. Class declarations end with a closing brace and a semicolon. Example 1

class Cat
unsigned int Age;
unsigned int Weight;
void Meow();

Cat  Frisky;
Frisky.Age = 8;
Frisky.Weight = 18;


class Car
public:                            // the next five are public

void Start();
void Accelerate();
void Brake();
void SetYear(int year);
int GetYear();

private:                           // the rest is private

int Year;
Char Model [255];
};                                 // end of class declaration

Car OldFaithful;                   // make an instance of car
int bought;                        // a local variable of type int
OldFaithful.SetYear(84) ;          // assign 84 to the year
bought = OldFaithful.GetYear();    // set bought to 84
OldFaithful.Start();               // call the start method


DO declare member variables private. DO use public accessor methods. DON'T try to use private member variables from outside the class. DO access private member variables from within class member functions.

Implementing Class Methods

As you've seen, an accessor function provides a public interface to the private member data of the class. Each accessor function, along with any other class methods that you declare, must have an implementation. The implementation is called the function definition.

A member function definition begins with the name of the class, followed by two colons, the name of the function, and its parameters. Program below shows the complete declaration of a simple Cat class and the implementation of its accessor function and one general class member function.

Implementing the methods of a simple class.

1:   // Demonstrates declaration of a class and
2:   // definition of class methods,
4:   #include <iostream.h>      // for cout
6:   class Cat                   // begin declaration of the class
7:   {
8:     public:                   // begin public section
9:       int GetAge();           // accessor function
10:      void SetAge (int age);  // accessor function
11:      void Meow();            // general function
12:    private:                  // begin private section
13:      int itsAge;             // member variable
14:  };
16:  // GetAge, Public accessor function
17:  // returns value of itsAge member
18:  int Cat::GetAge()
19:  {
20:     return itsAge;
21:  }
23:  // definition of SetAge, public
24:  // accessor function
25:  // returns sets itsAge member
26:  void Cat::SetAge(int age)
27:  {
28:     // set member variable its age to
29:     // value passed in by parameter age
30:     itsAge = age;
31:  }
33:  // definition of Meow method
34:  // returns: void
35:  // parameters: None
36:  // action: Prints "meow" to screen
37:  void Cat::Meow()
38:  {
39:     cout << "Meow.\n";
40:  }
42:  // create a cat, set its age, have it
43:  // meow, tell us its age, then meow again.
44:  int main()
45:  {
46:     Cat Frisky;
47:     Frisky.SetAge(5);
48:     Frisky.Meow();
49:     cout << "Frisky is a cat who is " ;
50:     cout << Frisky.GetAge() << " years old.\n";
51:     Frisky.Meow();
52;      return 0;
53: }
Output: Meow.
Frisky is a cat who is 5 years old.

Analysis: Lines 6-14 contain the definition of the Cat class. Line 8 contains the keyword public, which tells the compiler that what follows is a set of public members. Line 9 has the declaration of the public accessor method GetAge(). GetAge() provides access to the private member variable itsAge, which is declared in line 13. Line 10 has the public accessor function SetAge(). SetAge() takes an integer as an argument and sets itsAge to the value of that argument.
Line 11 has the declaration of the class method Meow(). Meow() is not an accessor function. Here it is a general method that prints the word Meow to the screen.

Line 12 begins the private section, which includes only the declaration in line 13 of the private member variable itsAge. The class declaration ends with a closing brace and semicolon in line 14.

Lines 18-21 contain the definition of the member function GetAge(). This method takes no parameters; it returns an integer. Note that class methods include the class name followed by two colons and the function name (Line 18). This syntax tells the compiler that the GetAge() function that you are defining here is the one that you declared in the Cat class. With the exception of this header line, the GetAge() function is created like any other function.

The GetAge() function takes only one line; it returns the value in itsAge. Note that the main() function cannot access itsAge because itsAge is private to the Cat class. The main() function has access to the public method GetAge(). Because GetAge() is a member function of the Cat class, it has full access to the itsAge variable. This access enables GetAge() to return the value of itsAge to main().

Line 26 contains the definition of the SetAge() member function. It takes an integer parameter and sets the value of itsAge to the value of that parameter in line 30. Because it is a member of the Cat class, SetAge() has direct access to the member variable itsAge.

Line 37 begins the definition, or implementation, of the Meow() method of the Cat class. It is a one-line function that prints the word Meow to the screen, followed by a new line. Remember that the \n character prints a new line to the screen.

Line 44 begins the body of the program with the familiar main() function. In this case, it takes no arguments and returns void. In line 46, main() declares a Cat named Frisky. In line 47, the value 5 is assigned to the itsAge member variable by way of the SetAge() accessor method. Note that the method is called by using the class name (Frisky) followed by the member operator (.) and the method name (SetAge()). In this same way, you can call any of the other methods in a class.

Line 48 calls the Meow() member function, and line 49 prints a message using the GetAge() accessor. Line 51 calls Meow() again.

C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


Be the first one to add a comment

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Charles
arraycopy example in Java
Action listeners in JSF
Automatically Including Preludes and Codas in JSP
Using realloc() Function in C
Handling multiple buttons in HTML Form in Struts
Fopen and Getc implementation program in C
Pointers to Structures example program in C
Pointers vs. Multi-dimensional Arrays in C
getch and ungetch in C
Bitwise Operators in C
Variables and Arithmetic Expressions in C
Differences between JavaServer Faces technology and Struts
assert() example program in C++
'double buffering' Sample program in J2ME
Converting Default Function Arguments in C++ to Java

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Using cout.width() in C++
Calculating total based on the given quantity and price in C++
Difference between Procedural, Structured, and Object-Oriented Programming
Dot (.) vs Arrow (->) to access data members in C++
Constructors and Destructors in C++
Calculate average using Two-Dimensional Array in C++
assert() example program in C++
C++ Recursion function explained using Fibonacci series
cin.ignore() in C++
Using peek() and putback() with cin in C++
Programming errors a compiler will detect in C++
Multiple statements in for loops in C++
Using Comments in a C++ Program
Using cout in C++
Sorting an array of Strings in C++
Most Emailed Articles (in C++)
Using cout.width() in C++
Two-Dimensional Array Manipulation in C++
Sorting an array of Strings in C++
Using cout in C++
Public versus Private members in C++
Interface Versus Implementation in C++
this Pointer in C++
Printing values in DEBUG mode in C++
File in C++ - Writing text to a file in C++
while loop in C++
Compute the square root of the sum of the squares of an array in C++
Getting Started with C++
C++ Sample Program for Allocating, using, and deleting pointers.
How to handle Exceptions in C++
Multiple inheritance example in C++