Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

C++ Class

Posted on 2004-07-31
5
Medium Priority
?
501 Views
Last Modified: 2012-06-21
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
0
Comment
Question by:claracruz
  • 3
  • 2
5 Comments
 
LVL 19

Expert Comment

by:mrwad99
ID: 11684194
>> 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
0
 
LVL 4

Author Comment

by:claracruz
ID: 11684243
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

0
 
LVL 19

Expert Comment

by:mrwad99
ID: 11684296
>> 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
0
 
LVL 4

Author Comment

by:claracruz
ID: 11684414
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
0
 
LVL 19

Accepted Solution

by:
mrwad99 earned 2000 total points
ID: 11684563
>> The issue I have is that I really don't get the full gist of classes.

Right then.  I will explain this in the simplest terms I know how.

You are programming in C++.  C++ is what we call an object oriented language as opposed to a procedural language.  The latter is a language where we do not represent a program as a series of interacting objects but as a load of code that executes one line after another.  It is not considered to be good style nowadays.

Objects.  That term may be puzzling.  Let me take a simple example that I was first introduced to: a light bulb.  This plain old light bulb can have two things done to it: you can turn it on or you can turn it off. In a C++ program, say representing this lightbulb, we could represent it as a CLASS.  The term class literally means a class of objects; we are of the human class, a tiger is of the animal class etc etc.  Of course, they are very general terms, but we will stick with them for the minute.

So back to our lightbulb.  I have already mentioned that it can do two things.  If we wanted to, say, turn this lightbulb on we would of course need to create a lightbulb first.  We can do this, but first we have to let our C++ compiler know that this lightbulb object exists.  We do this by declaring a class to represent it.

class Lightbulb
{
};

Easy.  We could create a lightbulb by stating

Lightbulb lb

where I have created a lighbulb that is called lb.

This is all very nice but not very useful.  We need something interesting so we can make the lightbulb do some work.  Lets add a method to turn the bulb on and then off...

class Lightbulb
{
public:
      void TurnOn();
      void TurnOff();
};

...like that.  But as yet, there is no body defined for these two functions, so we need to say exactly what the functions TurnOn() and TurnOff() do.  

(As a sidenote,  if I had stated

Lightbulb lb;
lb.TurnOn();

the compiler would give me a linker error since I am telling it that I want to use the function TurnOn() yet have not given any code for this function !)

So what we normally do is add the code for the functions like this:

void Lightbulb::TurnOn()
{
      // Do something to turn the bulb on
}

void Lightbulb::TurnOff()
{
      // Do something to turn the bulb off
}

Now, regarding your question as to where what code should be where, C++ programming style dictates that the definition of any class should go in a header file.  The implementation of the class's functions should go in a .cpp (or .cc if you use UNIX/LINUX)

So according to this we would have two files:

// lightbulb.h
class Lightbulb
{
public:
      void TurnOn();
      void TurnOff();
};

// lightbulb.cpp
void Lightbulb::TurnOn()
{
      // Do something to turn the bulb on
}

void Lightbulb::TurnOff()
{
      // Do something to turn the bulb off
}

I have called them lightbulb.h and lightbulb.cpp.  You can call them whatever you want, but make sure it describes what is in the file.  I normally call the file the name of the class.  

Now, this convention does not need to be stuck to, indeed when I am quickly building a class I normally put all the implementation and the definition in one file (usually the same one as my main() method) but this is just to get things going quickly.  The one good reason for separating .h and .cpp files however is that if you want to distribute your code (say, you designed a fantastic world-dominating lightbulb class that has state of the art code for turning the bulb on and off, you would want other people to be able to create one of your lighbulbs, like I did above with

Lightbulb lb;

but you would not want them to see your .cpp file which would give your code away.  So how can you do this ?  How can you show people what methods they can use, without showing them the code that does it ?  This is the solution: you would compile your .cpp code into a DLL (on Windows, or binary on Unix/Linux) so that it became unreadable, then distribute your header file.  So all your customers would know is

class Lightbulb
{
public:
      void TurnOn();      // Turn the lightbulb on
      void TurnOff();      // Turn the lightbulb off
};

i.e. they can make an object of class Lightbulb, and can call TurnOn() or TurnOff() on that object.  Note that you would add comments too like I have done so that customers know exactly what a method does.

** In essence, this is hiding the implementation (.cpp) from the Interface (.h).  Why bother someone with *how* something works ?  As long as they can get it to work, there is no need to bother them with the detail **

So that is the overview of classes you asked for.  I hope it is clearer now.  That should have answered 1) and 2) of your last post.

___________________________________________

Now your problem is a little more specific.  You are dealing with people, specifically customers,  and they have some sort of account I understand.  So this is simple to represent.

Since you are dealing with Customers, you will need to be creating instances of customers (customer objects) so that is why you would need a customer class.  However, you also have two sub-types of customers, individual and business.  Right then.

If you remember above I said that Animal and Human where examples of classes.  I also said they were very general, i.e. not specific.  We can have male humans, female humans, and tigers and lions.  So what C++ allows us to do is expand these classes by Inheritance.  Basically inheritance means that we create classes that are like another class, but expand it slightly to become more specialised.  An example will help.

class Animal
{
public:
      void Eat() {} ;
      void Sleep() {};
}

An animal can eat and it can sleep; two things *all* animals do.  But a lion can do more specific things than that, like Roar, that all animals *cannot* do.  So what we do is create a Lion class that inherits from Animal

class Lion : public Animal
{
      void Roar() {};
}

Now, since Lion inherits from Animal, it obtains all of the methods declared public in Animal, so even though I did not state explicitly that Lion contains a method Eat(), it still does, since it has *inherited* it from Animal, along with Sleep().  So I could say

Lion l;
l.Eat();

and it would be perfectly legal.

I could go on creating classes like Bird and Fish etc etc that would all derive from Animal adding functionality unique to them, but I think (and hope) you get the idea.

So back to your question.  I hope you can see that in order to do your program you will need three classes:

class Customer
{
};

class BusinessCustomer : public Customer
{
};

class IndividualCustomer : public Customer
{
};

(PS I hope I have got the idea right here, you may need separate classes you may not depending on what you have been taught.  But I would think this is the way to go about it)

The two classes BusinessCustomer and IndividualCustomer add functionality to the Customer class.  You said "The customer type determines the rate they will be charged per unit of usage. " so there is one difference you can see immediately that is unique for the class in question.

Please ask if you are still not sure, I hope I have clarified your concern.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
Suggested Courses

885 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question