Tutorial on Classes and Members in C++

By: Abinaya Emailed: 1757 times Printed: 2444 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

A class is just a collection of variables--often of different types--combined with a set of related functions.

One way to think about a car is as a collection of wheels, doors, seats, windows, and so forth. Another way is to think about what a car can do: It can move, speed up, slow down, stop, park, and so on. A class enables you to encapsulate, or bundle, these various parts and various functions into one collection, which is called an object.

Encapsulating everything you know about a car into one class has a number of advantages for a programmer. Everything is in one place, which makes it easy to refer to, copy, and manipulate the data. Likewise, clients of your class--that is, the parts of the program that use your class--can use your object without worry about what is in it or how it works.

A class can consist of any combination of the variable types and also other class types. The variables in the class are referred to as the member variables or data members. A Car class might have member variables representing the seats, radio type, tires, and so forth.


New Term: Member variables , also known as data members , are the variables in your class. Member variables are part of your class, just like the wheels and engine are part of your car.

The functions in the class typically manipulate the member variables. They are referred to as member functions or methods of the class. Methods of the Car class might include Start() and Brake(). A Cat class might have data members that represent age and weight; its methods might include Sleep(), Meow(), and ChaseMice().


New Term: Member functions , also known as methods , are the functions in your class. Member functions are as much a part of your class as the member variables. They determine what the objects of your class can do.

Declaring a Class

To declare a class, use the class keyword followed by an opening brace, and then list the data members and methods of that class. End the declaration with a closing brace and a semicolon. Here's the declaration of a class called Cat:

class Cat
{
unsigned int  itsAge;
unsigned int  itsWeight;
Meow();
};

Declaring this class doesn't allocate memory for a Cat. It just tells the compiler what a Cat is, what data it contains (itsAge and itsWeight), and what it can do (Meow()). It also tells the compiler how big a Cat is--that is, how much room the compiler must set aside for each Cat that you create. In this example, if an integer is two bytes, a Cat is only four bytes big: itsAge is two bytes, and itsWeight is another two bytes. Meow() takes up no room, because no storage space is set aside for member functions (methods).

A Word on Naming Conventions

As a programmer, you must name all your member variables, member functions, and classes. As you learned on Day 3, "Variables and Constants," these should be easily understood and meaningful names. Cat, Rectangle, and Employee are good class names. Meow(), ChaseMice(), and StopEngine() are good function names, because they tell you what the functions do. Many programmers name the member variables with the prefix its, as in itsAge, itsWeight, and itsSpeed. This helps to distinguish member variables from nonmember variables.

C++ is case-sensitive, and all class names should follow the same pattern. That way you never have to check how to spell your class name; was it Rectangle, rectangle, or RECTANGLE? Some programmers like to prefix every class name with a particular letter--for example, cCat or cPerson--whereas others put the name in all uppercase or all lowercase. The convention that I use is to name all classes with initial-capitalization, as in Cat and Person.

Similarly, many programmers begin all functions with capital letters and all variables with lowercase. Words are usually separated with an underbar--as in Chase_Mice--or by capitalizing each word--for example, ChaseMice or DrawCircle.

The important idea is that you should pick one style and stay with it through each program. Over time, your style will evolve to include not only naming conventions, but also indentation, alignment of braces, and commenting style.

 


NOTE: It's common for development companies to have house standards for many style issues. This ensures that all developers can easily read one another's code.

Defining an Object

You define an object of your new type just as you define an integer variable:

unsigned int GrossWeight;         // define an unsigned integer
Cat Frisky;                       // define a Cat

This code defines a variable called Gross Weight whose type is an unsigned integer. It also defines Frisky, which is an object whose class (or type) is Cat.

Classes Versus Objects

You never pet the definition of a cat; you pet individual cats. You draw a distinction between the idea of a cat, and the particular cat that right now is shedding all over your living room. In the same way, C++ differentiates between the class Cat, which is the idea of a cat, and each individual Cat object. Thus, Frisky is an object of type Cat in the same way in which GrossWeight is a variable of type unsigned int.


New Term: An object is an individual instance of a class.

Accessing Class Members

Once you define an actual Cat object--for example, Frisky--you use the dot operator (.) to access the members of that object. Therefore, to assign 50 to Frisky's Weight member variable, you would write

Frisky.Weight = 50;

In the same way, to call the Meow() function, you would write

Frisky.Meow();

When you use a class method, you call the method. In this example, you are calling Meow() on Frisky.

Assign to Objects, Not to Classes

In C++ you don't assign values to types; you assign values to variables. For example, you would never write

int = 5;               // wrong

The compiler would flag this as an error, because you can't assign 5 to an integer. Rather, you must define an integer variable and assign 5 to that variable. For example,

int  x;                // define x to be an int
x = 5;                 // set x's value to 5

This is a shorthand way of saying, "Assign 5 to the variable x, which is of type int." In the same way, you wouldn't write

Cat.age=5;             // wrong
???

The compiler would flag this as an error, because you can't assign 5 to the age part of a Cat. Rather, you must define a Cat object and assign 5 to that object. For example,

Cat Frisky;            // just like  int x;
Frisky.age = 5;        // just like  x = 5;

If You Dont Declare It, Your Class Wont Have It

Try this experiment: Walk up to a three-year-old and show her a cat. Then say, "This is Frisky. Frisky knows a trick. Frisky, bark." The child will giggle and say, "No, silly, cats can't bark."

If you wrote

Cat  Frisky;           // make a Cat named Frisky
Frisky.Bark()          // tell Frisky to bark

the compiler would say, No, silly, Cats can't bark. (Your compiler's wording may vary). The compiler knows that Frisky can't bark because the Cat class doesn't have a Bark() function. The compiler wouldn't even let Frisky meow if you didn't define a Meow() function.

 


DO use the keyword class to declare a class. DON'T confuse a declaration with a definition. A declaration says what a class is. A definition sets aside memory for an object. DON'T confuse a class with an object. DON'T assign values to a class. Assign values to the data members of an object. DO use the dot operator (.) to access class members and functions.

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

Comments(0)


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 Abinaya
How to compile a Java program - javac
The clone() Method in Java
Data Types in Java
JSP Example to connect to MS SQL database and retrieve records
faces-config.xml to DirectTraffic in the JSF Application
Enabling Expression Language Evaluation in JSP
Using malloc() Function in C
ActionErrors and ActionError in Struts
Open, Creat, Close, Unlink system calls sample program in C
Structures and Functions in C
Introduction to JSP expression language
Multi-dimensional Arrays in C (Explained using date conversion program)
A C program similar to grep command in UNIX
Type Conversions in C (String to Integer, isdigit() etc)
Basics of C

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++ )
Function overloading in C++
The Birth, history and need for C++
Dot (.) vs Arrow (->) to access data members in C++
Difference between Procedural, Structured, and Object-Oriented Programming
Using cout.width() in C++
Using cout in C++
Calculating total based on the given quantity and price in C++
strcat() and strncat() sample program in C++
assert() example program in C++
Matrix using nested for loops in C++
Demonstration of Prefix and Postfix operators in C++
C++ Recursion function explained using Fibonacci series
Public versus Private members in C++
while (1) Loops in C++
C++ Destructors Versus Java Finalization
Most Emailed Articles (in C++)
A Brief History of C++
Difference between Procedural, Structured, and Object-Oriented Programming
C++ and Object-Oriented Programming
Getting Started with C++
Using cout in C++
Using Comments in a C++ Program
Using functions in C++
How to use Enumerated constants in C++
Demonstration of Prefix and Postfix operators in C++
The if Statement in C++
Advanced if Statements in C++
Use of Conditional (Ternary) Operator in C++
Demonstrating global and local variables in C++
Passing parameters to a function by value in C++
Returning values from a function in C++