Link to home
Start Free TrialLog in
Avatar of claracruz
claracruz

asked on

C++ Class

G'day experts,

Please I need help with Classes in C++, this is my first time working with them, I am having trouble understaning its implementation.

Please have a lok at the following code, this is in my customer.h file;
class Customer {

      int prev; // previous reading
      int cur; // current reading
      char type; // type of customer (individual=I, business=B)
      char name[25];
      char address[50];
      char telephone[15];
      int lastMeterReading;
      int AccountNumber, confirm;
      ofstream outCustomer, outAccountNum; //output file
      ifstream inAccountNum; //input file

      /*the below method is private and used only from within this
       class and transparent to oustide function*/
      bool stringCheck(char*,int);

public:
      void add(int);
      bool compare(char*);
      void display();
      char* returnName();
      
unsigned int GasUsage()
      {
            // for wrap-around counter.
            // 33000 is the wrap-around point
            if(prev>cur)
                  return 33000-(prev-cur);
            else
                  return cur-prev;
      }

      float AmountDue()
      {
            if(type=='I')
            {
                  return float(GasUsage()*0.40);
            }
            else if(type=='B')
            {
                  return float(GasUsage()*0.36);
            }
            else // type=0 (error)
            {
                  return 0;
            }
      }
      void Display()
      {
            cout << "Customer name : " << name << '\n';
            cout << "Gas usage : " << GasUsage() << '\n';
            
            // check if there is an error in customer code
            if(type=='I'||type=='B')
            {
                  cout << "Expanded rate : " << type << '\n';
                  cout << "Amount due : " << AmountDue() << '\n';
            }
            else // cust[a].type=0 (error)
            {
                  cout << "***ERROR***\n";
            }
      }

};

void Customer::add(int flag)
{
      
      while (!cin.get()) {};

      if (flag==1)
      {

            outCustomer.open("customer.dat", ios::app); // opens file in append mode.
            
      //generate new account number
            inAccountNum.open("account.dat", ios::in);//assign file to input stream from account number


            if (inAccountNum.is_open())
            {
                  inAccountNum >> AccountNumber; //get account number from account.dat
                  inAccountNum.close();
            }
            else
            {
                  cout << "the file has not been open";
            }

            AccountNumber = AccountNumber + 1;//add one to account number
            outAccountNum.open("account.dat");
            outAccountNum << AccountNumber;//replace account number in account.dat with new figure for future use
            outAccountNum.close();

            //Get customer details, ask for input until acceptable input is received.

            do
            {
                  cout << "\n Enter customer's full name : ";
                  cin.getline(name,1000,'\n');
                  strupr(name);
            }while (!stringCheck(name,1));//checks that acceptable input is received.

            do
            {
                  cout << "\n Enter customer's address : ";
                  cin.getline(address,1000,'\n');
                  strupr(address);
            }while(!stringCheck(address,2));


            do
            {
                  cout << "\n Enter customer's telephone number : ";
                  cin.getline(telephone,1000,'\n');
            }while (!stringCheck(telephone,3));

            do
            {
                  cout << "\n Enter customer's current meter reading : ";
                  cin >> lastMeterReading;
            }while (33000 <= (lastMeterReading));

            do
            {
            cout << "\n Enter customer type(I=individual B= business) : ";
            cin >> type;
            }while (type > 'I');

            
            //Confirm Information
            cout << "\n" << "\n"<< "Confirm Customer Details (Enter 1. to confirm new account or 2. to cancel transaction);";
            cin >> confirm;
            cout << "\n";


            switch(confirm)
            {
 
            //save customer details to file and display ID, Gas meter Reading and Customer type.
            system("CLS");
            case 1: cout << "     New Account Created for:" << " " << name << "\n";
            
            cout <<"\n     ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»";
            cout <<"\n     º                                                    º";
            cout <<"\n     º CUSTOMER ASSIGNED ID:"<<" "<<AccountNumber<<"           ";
            cout <<"\n     º Gas Meter Reading Set To:"<<" "<<lastMeterReading<<"    ";
            
            if (type == 'I' || type == 'i')
            {
            cout <<"\n     º ACCOUNT TYPE CREATED: INDIVIDUAL CUSTOMER ACCOUNT        ";
            }
            else if (type == 'B'|| type =='b')
            {
                  cout <<"\n     º ACCOUNT TYPE CREATED: BUSINESS CUSTOMER ACCOUNT      ";
            }

            else
            {
                  cout <<"\n     º ACCOUNT TYPE CREATED: ***ERROR***     ";
            }
            cout <<"\n     º                                                    º";
            cout <<"\n     ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ\n";


            outCustomer << AccountNumber << '\t' << name << '\t' << address << '\t' << telephone << '\t'
            << lastMeterReading<< '\t' << type << '\n';
            outCustomer.close();
            cout << "\n"<< "     Details saved to Customer file." << "\n";
                  break;
      
                  //cancel transaction
            case 2: cout << "Transaction Cancelled!!" << "\n";
                  break;
                  default: cout << "Invalid Option;";
            }
                        
      }
      else //if editing customer information
      {
            
            do
            {
                  cout << "\n Enter new address for customer : ";
                  cin.getline(address,50,'\n');
                  strupr(address);
            }while(!stringCheck(address,2));


            do
            {
                  cout << "\n Enter new telephone number for customer : ";
                  cin.getline(telephone,15,'\n');
            }while (!stringCheck(telephone,3));
      }
}


//will be used to search for customer in customer file by name.
bool Customer::compare(char *string)
{
      unsigned int length=strlen(string),i,same=0;
      
      
      for (i=0;i<length;i++)
      {
            if (string[i] == name[i])
                  same++;
            else
                  same = 0;
      }

      if (same==length)
            return true;
      else
            return false;
}


//this function used to validate user inputs when creating new customer account.
bool Customer::stringCheck(char* s,int n)
{
      unsigned int i;
      
      if (n==4)// Validate customer type input, check if type is empty string
      {                              
            if (strlen(s)==0)
            {
                  cout << "\n(Please Enter [I] for individual or [B] for business) : " << "\n\n";
                  return false;
            }
            else
                  return true;
      }

      if (n==1)// Validate customer name input, check that string not empty or over 25 charcters
      {
                              
            if (strlen(s)==0 || strlen(s) > 25)
            {
                  cout << "\nName cannot be empty or more than 25 characters";
                  return false;
            }
            else
                  return true;
      }

      if (n==2)// validate customer address input
      {
                              
            if (strlen(s)==0 || strlen(s) > 50)
            {
                  cout << "\nAddress cannot be empty or more than 50 characters";
                  return false;
            }
            else
                  return true;
      }



      else if (n==3)// validate customer telephone number, ensure string not emapty and values are numeric
      {
            for (i = 0; i < strlen(s); i++)
            {
                  if (isalpha(s[i]))
                  {
                        cout << "\nPlease enter Numeric Values Only";
                        return false;
                  }
                  
            }

            if (strlen(s)==0 || strlen(s) > 15)
            {
                  cout << "\nTelephone cannot be empty or more than 15 characters\n";
                  return false;
            }
            else
                  return true;
      }
      else
            return true;

}


void Customer::display(void)
{
      cout << setiosflags(ios::left) << setw(20)<<name;
      cout << setw(25)<<address<<setw(13)<<telephone<<setw(22)<<lastMeterReading<<"\n";
}

char* Customer::returnName(void)
{
      return name;
}



This code is my class and I call it from my .cpp file.
THE QUESTION:
1.  please go through the code and let me know if this is way too much detail to be including in a class. I am not able to grasp the level of info that needs to be in a class. Also I am very new to c++ so some of the code might not be great, please point these out and explain what am doing wrong and how to correct this error.

2.  If this code does not a Class make, please advise me on what am doing wrong, and explain with as much detail as possible.

3. any additional refernce to good c++ class tutorials is appreciated.

thank you
Avatar of mrwad99
mrwad99
Flag of United Kingdom of Great Britain and Northern Ireland image

>> Please have a lok at the following code, this is in my customer.h file;

Right, to begin with, you only need to add functionality to a class that you are actually going to use.  I don't know what the specification of this project you are working on is, so if you have functions in there that you will never use, get rid of them.

A few points:

      unsigned int GasUsage()
      {
            // for wrap-around counter.
            // 33000 is the wrap-around point
            if(prev>cur)
                  return 33000-(prev-cur);
            else
                  return cur-prev;
      }

Why is this in the class declaration ?  Normally you would leave defintions of functions in the declaration if they were small enough to be inline.  This could be inline, but would be better written as

      unsigned int GasUsage()
      {
            return (prev>cur) ?  33000-(prev-cur) : cur-prev;
      }

Also AmountDue() could be better written using a switch statement:

switch (type) {
case 'I':
      return float(GasUsage()*0.40);
      break;
case 'B':
      // etc
default:
      return 0;
}

In general use switch statements instead of multiple if statements where you can (i.e. for primitive types).  This AmountDue() function and Display() should *not* be in the header file but in the .cpp file.

char* Customer::returnName(void)
{
return name;
}

That should definitely be inline :)  In general functions of one line are ideal candidates to go inline, any more than that is defeating the object.

Regarding C++ tutorials for classes, have a look at http://newdata.box.sk/bx/c/htm/ch06.htm
Avatar of claracruz
claracruz

ASKER

Thank for replying so quickly,

Wht about the code that is creating my a new customer account, is it ok, to do everythin I am doingin the class, that is

open data file
save to data file
display confirmation. e.t.c.

I don't actually know what is meant by inline, what does this mean and what is the differnce.

//This AmountDue() function and Display() should *not* be in the header file but in the .cpp file.
WHY???? Plwease explain

>> I don't actually know what is meant by inline, what does this mean and what is the differnce.

An inline function is basically one that is declared where it is defined, i.e. you give the function body as well as the prototype.  EG

// myClass.h
class myClass
{
public:
      void InlineFunction() { cout << "This is an inline function" << endl;
void NotInlineFunction();
};

// myClass.cpp
void myClass::NotInlineFunction()
{
      cout << "This function is not inline" << endl;
}

You can see that the function that is not inline (NotInlineFunction) has its implementation in the .cpp file, whereas the inline function has the implementation in the header file.  

We normally  use inline functions as they provide faster execution.  Read http://www.parashift.com/c++-faq-lite/inline-functions.html for more details.

>> Wht about the code that is creating my a new customer account

Well if that code works then it is ok, I have not gone through it in detail.  If you have any specific problems then mention them, otherwise it seems ok.

>> //This AmountDue() function and Display() should.....

These functions are too big to be inline.  They should be implemented in the .cpp file.  i.e.

// in .cpp file
     float Customer::AmountDue()
     {
          if(type=='I')
          {
               return float(GasUsage()*0.40);
          }
          else if(type=='B')
          {
               return float(GasUsage()*0.36);
          }
          else // type=0 (error)
          {
               return 0;
          }
     }
     void Customer::Display()
     {
          cout << "Customer name : " << name << '\n';
          cout << "Gas usage : " << GasUsage() << '\n';
         
          // check if there is an error in customer code
          if(type=='I'||type=='B')
          {
               cout << "Expanded rate : " << type << '\n';
               cout << "Amount due : " << AmountDue() << '\n';
          }
          else // cust[a].type=0 (error)
          {
               cout << "***ERROR***\n";
          }
     }

HTH
Ok, cool!!

I'm still a bit lost though.

The whole code works. It is not the problem.
The issue I have is that I really don't get the full gist of classes.

I think the folowing question should help clarify: (forgive any questions that may appear stupid)

1. what exactly is the use for a .h file.
2. Do classes always have to be declared in a .h file
3.Basicaly for the program I am working on, There are two types of customers, business(B) and individual(I). The customer type determines the rate they will be charged per unit of usage. The program needs to create customer accounts, store them in a file, calcualte usuage, display data and print invoice. I am required to have a customer class.

The question is:
          1. why would I need a customer class for this progam?
          2. What exactly would I be using the customer class to achieve?
          3. what determines that an entity within a program should be a class?

Please explain as if to a four year old, I am just starting to learn c++.

thank you
ASKER CERTIFIED SOLUTION
Avatar of mrwad99
mrwad99
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial