C++ Classes

How to create a class

A class is a type that encapsulates a fixed number of data components (data members) with the functions (called member functions) that manipulate them.

Typically 2 files used to define a classe

Define the class in file date.h (specification file)
    

class Date {

    int day, //internal storage scheme
                  month, //this is private to the class
         
year;

         char *message; //string message reflecting date

   public:
     void new_date(int,int,int); //method to change the date

          char* give_date(); //report date
};

Now define the methods in file date.cpp (implementation file)

#include "date.h"

void date::new_date(int d, int m, int y)
{
   day = d;
   month=m;
   year=y;
}

void date::give_date()
{
   char *buf= new char[80];

   sprintf(buf, "%s %d, %d", mname[month],day,year);


   return buf;
}

 

//constructor

date::date(....)
{ //...code here }


//destructor
date::~date()
{ //...code here }

 

 

 

Create an instance of the class

date d; //will call default constructor automatically

Abstract Class

 

An abstract class is a class which has one or more pure virtual methods:

  • Own pure virtual functions Inherited (without overriding) of pure virtual functions
  • Abstract class may have subclasses but no instances:
            No object of an abstract class can be created:
            An abstract class cannot be used as an argument type.
            An abstract class cannot be used as function return

use the keyword abstract

class Draw it
{

     virtual void print();

}

See an example of abstract class, a subclass and a program using it.
  


  

Interface Class

 

An abstract class is a class which all methods are abstract (pure virtual)

 

© Lynne Grewe