CyberArmy Academy | CyberArmy Services & Support | Open Source Institute | CyberArmy Intelligence & Security | CyberArmy Projects

[Library Index]

[View category: C++] [Discuss Article]

Practical C++ Part 10 : Classes

Article is yet to be rated
Author:      Rae
Submitted:      28-Apr-2007 19:41:03
Imported From:      The CyberArmy University (original author: Rae)


Practical C++ Part 10 : Classes
A major change in C++ from C was the Object Oriented Programming approach (OOP). Instead of having structures, C++ has defined a new kind of data type called 'class'. A variable of the type class is called its 'object'. The classical definition of an object is that it is a runtime instance of a class. These definitions are derived from real-life objects and the classes of objects in the world surrounding us.

A class has the same format as that of a structure with one exception, it also has functions inside the class definition itself. The general format of a class is represented as:
class <name> 
{
  data member;
  data member;
  
  public :
  
  member function;
  member function;

}<object name>;
Here 'public' means that the member functions written in the public mode can be called by the object directly, using the dot (.) operator. Whereas the private data members cannot be accessed directly by the object, but have to accessed with the help of member functions. This particluar OOP concept is called 'data hiding'. Take a look at the program given below :-
#include<iostream.h>
#include<conio.h>

class car
{ 
  int num;
  char color[10];
  char model[15];
  float mileage;

  public :

  void inputdata()
  {  
    clrscr();
    cout<<"Enter the car id number"<<endl;
    cin>>num;

    cout<<"Enter the color and model of the car"<<endl;
    cin>>color>>model;

    cout<<"Enter the mileage in km/l"<<endl;
    cin>>mileage;
  }

  void outputdata()
  {
    clrscr();
    cout<<"Car ID = "<<num<<endl;
    cout<<"Color = "<<color<<endl;
    cout<<"Model = "<<model<<endl;
    cout<<"Mileage = "<<mileage<<endl;
    getch();
  }
};

void main()
{
  clrscr();
  car obj;

  obj.inputdata();
  obj.outputdata();
  
  getch();
}
The above code is pretty much self explanatory. But for the heck of it, the 'obj' variable is the object of type 'car'. It has four data members and two member functions which access the data members and perform necessary manipulation. Take particular care about the public functions. Also note the semi colon at the end of the class definition.

References :-
  • Object Oriented Programming using C++ by E Balagurusamy
  • Software Engineering : A Practitioner's Approach by Roger Pressman
  • UML Distilled by Martin Fowler and Kendall Scott
Written by Rae (28 January 2005)

Rae is a member of CAU Knowledge-Bank Tutorial Writers

This article was originally published by CyberArmy.net in the CyberArmy Library.

You must be logged in to vote on an article

About Us | Privacy Policy | Mission Statement | Help