Getting Started with C++: Classes

Author: Ronald S. Holland
at
Total Application Works






To visit my site

HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#


To contact us

© 2002 - 2016 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).)

  • <html>
    <head>
    <title>Example of a link </title>
    </head>
    <body>
    <a href="http://sumtotalz.com/TotalAppsWorks/CPP_Classes.html">
    Getting Started with C++: Classes </a>
    </table>
    </body>
    </html>


Introduction

c++, as a programming language, is widespread and can be found on nearly all computers. This tutorial assumes that you have some prior programming experience. It is not intended to be a comprehensive discussion on c++ or programming. As we ease into c++, we will briefly discuss the classes and structs. But first, what is a c++?

What is a c++?

C++ is an enhancement to C, with a few major additions. One major addition is the object-oriented approach. This approach deals with objects, which are instanitated classes (see Figure 2 below: Employee emp() ;). Classes are collections of data related to a single object type. Classes not only contain information regarding the real world object, but also methods to access the data. In addition, classes possess the ability to inherit from other classes.

Let's consider the class of automobile, which contains the set of all automobiles. A sampling might be:

  • Acura TL
  • BMW 5 series
  • Buick Century
  • Ford Explorer
  • Honda Pilot
  • Mazda6
  • Toyota Avalon
  • Toyota Highlander
  • Volvo S60
  • etc.
The set/get methods usually will be the only way to modify the variables in this structure, and they are usually the only way to access the variables in a class. By allowing only a class to access the data makes the programs more modular; the principle itself is called encapsulation. This allows the implementation to change more easily because only the class itself should have to rely on the changes. For example, a set method might be setCruise_Control.

In real-life, complex objects are often built from smaller, simpler objects. This process, in c++ is called object composition. For example, a car is built using a:
Object
     Methods       
metal frame,
ignition,
  • Turn on
  • turn off
engine,
tires,
transmission,
  • Shift to 1st
  • Shift to 2nd
  • Shift to 3rd
  • Shift to neutral
  • Shift to reverse
steering wheel,
  • Turn left
  • Turn right
  • Go straight
wind shield,
brakes,
  • Apply
  • Release
electronic stability control,
  • counter oversteer
  • counter understeer
ABS,
cruise control,
bucket seats,
digital clock,
AM/FM radio,
CD Changer,
gear shifter,
and a large number of other parts./b>
Figure 1: Object composition and methods


Class

If we were to implement Figure 1 as a class, it might look something like:

 
/************************************************
 * Automobile Class - this is pseudocode and as 
 * such, it is not compilable.
 ***********************************************/

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>

using std::cout;
using std::cin;
using std::endl;
using std::string;

class Automobile  {   
        // Declare member types
   Metal_frame    mf ;
   Ignition       ign ;
   Engine         eng ;
   Tires          tires ;
   Transmission   trans ;
   Steering_Wheel sw  ;
   Wind_shield    ws  ;
   Brakes         brakes ;
   ABS            abs ;
   CruiseControl  cc ;
   DigitalClock   dc :
} 

int main() {
   automobile auto ;    

   retrun 0 ;
}
 
Figure 2: Automobile Class


Are structs and classes the same?

What is a struct?

In the following examples, we will use an Employee class, instead of the automobile class. A structure type is a user-defined data type. It consists of fields or members that can have different data types, known as members, grouped together under one name. If you compare this to a primitive array, an array consists of multiple items/elements that can be addressed using one name/reference. In addition, all of the elements in an array must be of the same data type. In C++, a structure is the same as a class except that its members are public by default. The struct keyword defines a structure type and/or a variable of a structure type.

 
/************************************************
 * Employee.cpp
 ***********************************************/

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>

using std::cout;
using std::cin;
using std::endl;
using std::string;

    // Declare Employee struct type
    // Declare Employee struct type
struct Employee {   
        // Declare member types
   char name[35] ;
   char address[35] ;
   char city[25];
   char state[25];
   char dob[25];
   int age;   
   long ss;
   float weight;
   float salary;
} ;   // Define object of type Employee

int main() {
   int len ;

   struct Employee grace;   // C style structure declaration
   Employee john;           // C++ style structure declaration
   grace.age  = 25;        // assign values to members
   strcpy( grace.name , "Mary" ) ;
   john.age   = 27;

   cout << "The length of grace.name is: " << ( len = strlen(grace.name) ) << endl ;  
   cout << "The value of grace.name is: " << grace.name << endl ;  
}
 
Figure 3: Program using struct


We will explore a class in the next section.

What is a class?

A class is an expanded concept of a data structure: instead of consisting of only data, it can contain both data and functions/methods. An object is an instantiation of a class. If you were to compare classes to primitive data, such as int variables, a class would be the data type (int) and an object would be the variable. Classes are generally declared using the keyword class which is followed by the name of the class. For an example, see the following format:

 
/************************************************
 * Employee.cpp
 ***********************************************/

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <string.h>

using std::cout;
using std::cin;
using std::endl;
using std::string;

using std::ostream;
using std::istream;
using std::ios;
using std::setw;

   // Declare Employee struct type
class Employee {  
   private: 
      struct Employee_Struct {   
        // Declare member types
         char * first_name ;
         char * last_name ;
         char * address ;
         char * city ;
         char * state ;
         char * dob ;
         int age;   
         char * ss;
         float salary;  
         long emp_ID;
} ;   // Define object of type Employee_Struct
	  
		 Employee_Struct es ;

   public: 
      Employee ( ) ;  // constructor
      Employee ( char *  fn, char *  ln, char *  addr,
		  char *  cty, char *  ste, char *  bd, int age_1,
		  char *  soc, float salry, long empID); 
 ~Employee() ;	 // denstructor 
      friend ostream &operator<<( ostream &, const string & ); 
      void setFirstName( char *  );
      char *  getFirstName();     
      void setLastName ( char *  );
      char *  getLastName();
      void setAddress ( char *  );
      char *  getAddress();
      void setCity ( char *  );
      char *  getCity();
      void setState ( char *  ); 
      char *  getState();
      void setDOB ( char *  );
      char *  getDOB();
      void setAge ( int );
      int getAge();
      void setemplID ( long );
      long getemplID();
      void setSS ( char * );
      char *  getSS();
      void setsalary ( float );
      float getsalary ();
	  char *  Strcpy( char * str1 , char * str2 ) ;

} ;   // Define object of type Employee


Employee::Employee (  ) { ;}
Employee::Employee ( char * fn, char * ln, char * addr,
		  char * cty, char * ste, char * bd, int age_1,
		  char * soc, float salry, long empID  ) {
  

}   

char *   Employee::Strcpy( char *  str1 , char *  str2 ) {
  int len = 0 , ii = 0 ;   

  return str1 ;
}
void Employee::setFirstName( char *  fn ) {
   es.first_name  = fn ; 
   cout << "es.first_name is: " <<  es.first_name << endl ;

}
char * Employee::getFirstName() {
   return es.first_name ;
}   
void Employee::setLastName ( char * ln ) {
   es.last_name = ln ;
   cout << "es.last_name is: " <<  es.last_name << endl ;
}
char * Employee::getLastName() {
   return es.last_name ;

}
void Employee::setAddress ( char * addr  ) {
   es.address = addr ;
   cout << "es.address is: " <<  es.address << endl ;

}
char * Employee::getAddress() {
	return es.address ;
}
void Employee::setCity ( char * city ) {
   es.city = city ;
   cout << "es.city is: " <<  es.city << endl ;

}
char * Employee::getCity() {
	return es.city ;
}
void Employee::setState ( char * state ) {
   es.state = state ;
   cout << "es.state is: " <<  es.state << endl ;
}
char * Employee::getState() {
	return es.state ;

}
void Employee::setDOB ( char * str  ) {
   es.dob = str ;
   cout << "es.dob is: " <<  es.dob << endl ;
}
char * Employee::getDOB() {
   return es.dob ;
}
void Employee::setAge ( int a ) {
   es.age = a ;
   cout << "es.age is: " << es.age << endl ;
}
int Employee::getAge() {
	return es.age ;

}
void Employee::setSS ( char * str ) {
   es.ss = str ;
   cout << "es.ss is: " << es.ss << endl ;

}
char * Employee::getSS() {

	return es.ss ;
}
void Employee::setemplID ( long ) {
   es.emp_ID ;
}
long Employee::getemplID() {
   return es.emp_ID ;
}
void Employee::setsalary ( float x) {
  es.salary = x ;  
}
float Employee::getsalary () {
   return es.salary ;
}
Employee::~Employee () {
   cout << "Exiting from destructor."  << endl ;

}
// Overloaded output operator for class Array 
ostream &operator<<( ostream &output, const string &a ) {
   int i;

   output << setw( 12 ) << a;


   return output;   // enables cout << x << y;
}


int main() {
   int emplID ;

    Employee emp() ;
   struct Employee  empStruct ;
  /* Employee emp( "George", "Wellington III", "123  Maple Terrace",
		  "Cary", "NC", "12/25/80", 31,
		  "123-45-9887", 6589.99, 567489) ;  */
   cout << "Enter employee ID" << endl ;
   cin >> emplID ;
   empStruct.setFirstName( "George" ) ;
   empStruct.setLastName ( "Wellington III" ) ;
   empStruct.setAddress ( "123  Maple Terrace" );
   empStruct.setCity( "Cary" ) ;
   empStruct.setState ( "NC" ) ;
   empStruct.setDOB( "12/25/80" ) ;
   empStruct.setAge( 31 ) ; 
   empStruct.setemplID ( emplID ) ;
   empStruct.setSS ( "123-45-9887" ) ;
   empStruct.setsalary( 6589.99 ) ;


   cout << "Exiting from program." << endl ;
   return 0 ;
}
 
Output
This is the Employee class from

Ronald S. Holland

         @

Total Application Works.


Employee constructor called for the purpose of initializing or setup.

Enter employee ID
777777
es.first_name is: George
es.ln is: Wellington III
es.address is: 123  Maple Terrace
es.city is: Cary
es.state is: NC
es.dob is: 12/25/80
es.age is: 31
es.emp_ID is: 777777
es.ss is: 123-45-9887
Exiting from program.
Exiting from destructor.
 
Figure 4: Program using class


In Figure 4, you will note that the format for declaring a class is:

 
class class_name {
   public:
      declare variables
   protected:
      declare variables
   private:
      declare variables

   public:
      define methods  
}
Figure 5: Declaring a class


In the above Figure 5, access to the data and methods is restricted by the following access specifiers:

  • Public members are accessible from any point the object is visible. There are some parts of the class are supposed to be available to anyone using the class; these parts are designated public class functions. Think of a class as though it were an appliance like a computer: the public parts of the class correspond to the parts of the computer that you can use/touch on an everyday basis, such as the:
    • keyboard,
    • on/off button,
    • screen,
    • mouse,
    • etc.
    The items you normally don't touch that might be considered protected/private are the:
    • motherboard,
    • RAM,
    • disk drive,
    • memory,
    • functions that read/write to the RAM,
    • functions that read/write to the internal disk drive,
    • etc.
    In Figure 4 above, you will note the following code snippet:
     
    
       Employee emp() ;
       struct Employee_Struct  empStruct ;
     

    Both class Employee and struct Employee_Struct are designated with public access.
  • protected members are accessible from members of their same class and from their friends, but also from members of their derived classes. An example is:
     
    
    friend ostream &operator<<( ostream &, const string & ); 
     

  • private members of a class are accessible only from within other members of the same class or from their friends. get/set type methods are usually the means by which private data is accessed (see Figure 4 above). All members of a class, data and methods, are private by default.

Consider some of these different access restrictions for a moment. Why would we want to declare something private instead of public? The idea is that some parts of the class are intended to be encapsulated/internal to the class. This allows us to implementing encapsulated features. If we consider the SQRT key on a calculator, the key pad is public and the SQRT code is private/protected. This corresponds to the protected or private parts of the class, the things that are necessary for the class to function, but that nobody who uses the class should need to know how it is coded. The great thing about this separation is that it makes the class easier to use (who would want to use a calculator where you had to be well aware of programming to know exactly how all of the functions work in order to use it?) The key idea is to separate the interface you use from the way the interface is supported and implemented.

Classes must always contain two functions: a constructor and a destructor. The syntax for them is simple: the class name denotes a constructor (e.g., Employee()), a ~ (e.g., ~Employee()) before the class name is a destructor. The constructor is used to initialize variables, and the destructor is used to clean up on exit from the class/program, which includes freeing any memory that has been allocated. If it turns out that you don't need to actually perform any initialization, then you can allow the compiler to create a "default constructor" for you. Likewise, if the destructor is not required to perform any special tasks, the compiler can also write a default destructor.

The constructor is automatically called when the programmer creates an instance (see Figure 4 above) of the class. The only time the destructor is called is when the instance of the class is no longer needed, either when the program ends, this is when the class reaches the end of scope, or when its memory is deallocated using delete. Please note that neither constructors nor destructors return arguments! This means you do not want to (and cannot) return a value in them.

Conclusions

This tutorial is intended to be an introduction, and as such, is far from being an exhaustive description. In this tutorial, you have learned the basics of a:

  • Class;
  • struct;
    • All struct members are public by default.
  • class definition;
    • All class members are private by default.
  • class declaration;
  • access specifiers;
  • access specifier restrictions;
  • constructors and destructors;
  • instantiation;

Definitions

abstract data type

AFXWIN

    This is a header for the Microsoft Foundation Classes C++ library. It must be included in all MFC applications.

CFrameWnd

    The CFrameWnd class encapsulates the functionality of a Windows single document interface (SDI) frame window. A frame window is a window that frames an application.

object composition

    object composition (not to be confused with function composition) is a way to combine simple objects or data types into more complex ones.

CWinApp

    The CWinApp class is the base class from which you derive a Windows application object. An application object provides member functions for initializing your application (and each instance of it) and for running the application.

CStatic

    The CStatic class provides the functionality of a Windows static control. A static control is a control used to display text, to draw frames or lines separating other controls, or to display icons. A static control doesn't accept user input, but it can notify its parent of stylus taps if it's created with SS_NOTIFY style.

Encapsulation

    is the hiding of information in order to ensure that data structures and operators are used as intended and to make the usage model more obvious to the developer.

event handling

inheritance

    is the ability to create a class that derives properties from one or more base classes.

initinstance

    Override InitInstance to initialize each new instance of your application running under Windows. Typically, you override InitInstance to construct your main window object and set the CWinThread::m_pMainWnd data member to point to that window.

m_pMainWnd

    Holds a pointer to the application’s main window.

object-oriented

    is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their behaviors – to design applications and computer programs

pseudocode

    is a compact and informal high-level description of the operating principle of a computer program or other algorithm. It uses the structural conventions of a programming language, but is intended for human reading rather than machine reading.

SS_CENTER

    Designates a simple rectangle and displays the given text centered in the rectangle. The text is formatted before it is displayed. Words that would extend past the end of a line are automatically wrapped to the beginning of the next centered line.

Template

    is a unique class or pattern that can be used to build other software code.

WS_BORDER

    Creates a window that has a border.

WS_CHILD

    Creates a child window. Cannot be used with the WS_POPUP style.

WS_VISIBLE

    Creates a window that is initially visible.







HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

© 2002 - 2016 All Rights Reserved Total Application Works