7

How do I separate classes into multiple files? Here is my understanding so far:

  1. Create new class, and a ".h" and a ".cpp" file for it.
  2. You use #include classname.h in your main source file to import its contents.
  3. The Classname::Classname at the beginning of the source file is a Scope Resolution Operator.
  4. You can call functions from main by using the objects that you have declared.

I'm just confused about how to implement this in practice. I have created a working calculator program with all the classes in one source file:

#include <iostream>
using namespace std;

class Addition {
    public:
    float add(float x, float y) {
        float sum;
        sum = x + y;
        return sum;
    }
};

class Subtraction {
    public:
    float subtract(float x, float y) {
        float dif;
        dif = x - y;
        return dif;
    }
};

class Multiplication {
    public:
    float multiply(float x, float y) {
        float prod;
        prod = x * y;
        return prod;
    }
};

class Division {
    public:
    float divide(float x, float y) {
        float quot;
        quot = x / y;
        return quot;
    }
};

int op;
char cont;

int main() {
    do {
    cout << "Welcome to C++ Calculator v2!" << endl;
    cout << "Select the number for which operation you want to use: " << endl;
    cout << "1-Addition" << endl;
    cout << "2-Subtraction" << endl;
    cout << "3-Mutliplication" << endl;
    cout << "4-Division" << endl;
    cin >> op;

    if (op == 1) {
        float num1;
        float num2;
        Addition addObj;
        cout << "You have chosen Addition!" << endl;
        cout << "Enter the first number you want to add: " << endl;
        cin >> num1;
        cout << "Enter the second number you wat to add: " << endl;
        cin >> num2;
        float ans = addObj.add(num1, num2);
        cout << "The sum is " << ans << endl;
        cout << "Do you wish to continue? Y/N" << endl;
        cin >> cont;
    }

    if (op == 2) {
        float num1;
        float num2;
        Subtraction subObj;
        cout << "You have chosen Subtraction!" << endl;
        cout << "Enter the first number you want to subtract: " << endl;
        cin >> num1;
        cout << "Enter the second number you want to subtract: " << endl;
        cin >> num2;
        float ans = subObj.subtract(num1, num2);
        cout << "The difference is " << ans << endl;
        cout << "Do you wish to continue? Y/N" << endl;
        cin >> cont;
    }

    if (op == 3) {
        float num1;
        float num2;
        Multiplication multObj;
        cout << "You have chosen Multiplication!" << endl;
        cout << "Enter the first number you want to multiply: " << endl;
        cin >> num1;
        cout << "Enter the second number you want to multiply: " << endl;
        cin >> num2;
        float ans = multObj.multiply(num1, num2);
        cout << "The product is " << ans << endl;
        cout << "Do you wish to continue? Y/N" << endl;
        cin >> cont;
    }

    if (op == 4) {
        float num1;
        float num2;
        Division divObj;
        cout << "You have chosen Division!" << endl;
        cout << "Enter the first number you want to divide: " << endl;
        cin >> num1;
        cout << "Enter the second number you want to divide: " << endl;
        cin >> num2;
        float ans = divObj.divide(num1, num2);
        cout << "The quotient is " << ans << endl;
        cout << "Do you wish to continue? Y/N" << endl;
        cin >> cont;
    }

    } while (cont == 'Y' || cont == 'y');

    if (cont == 'N' || 'n') {
    cout << "Thanks for using my program, goodbye!" << endl;
    }

    return 0;
}

I know there is a lot easier way to make something like this, but I've used classes and objects instead for the sole purpose of practice.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
Carpetfizz
  • 8,707
  • 22
  • 85
  • 146
  • 1
    too much words, please, edit your post for better reading – gaussblurinc Aug 09 '12 at 13:43
  • ugh sorrry, for some reason I can't get the numbered lists to work, any idea how? – Carpetfizz Aug 09 '12 at 13:43
  • 1
    You need to seperate into declaration (.h) files and implementaion (.cpp) files. – Damian Aug 09 '12 at 13:45
  • 3
    since you're a beginner, here's a tip: *every* time you do copy/paste (a lot in your code), think twice: aren't you duplicating functionality? If the answer yes, put that functionality it in a seperate function or class. – stijn Aug 09 '12 at 13:45
  • see edit for numbered lists: you need an extra newline before them – stijn Aug 09 '12 at 13:46
  • @thanks for the edit and the tip stijn. And also, I did try to simply copy and paste one of the classes, and include the ".h" for it but it obviously didn't work. – Carpetfizz Aug 09 '12 at 13:48
  • if you refer to another post, please link it. – TemplateRex Aug 09 '12 at 13:48
  • well it doesn't have anything to do with this issue @rhalbersma, I was just saying it for those who saw my post about me trying to learn classes and objects. – Carpetfizz Aug 09 '12 at 13:53
  • @Carpetfizz If it doesn't have anything to do with your question, please leave it out. You should try to make your questions as concise as possible. – TemplateRex Aug 09 '12 at 13:54

4 Answers4

8

Ok, I will show you by doing your example:

subtraction.h

class Subtraction 
{
public:
 float subtract (float x, float y);
};

subtraction.cxx

#include "subtraction.h"

float Subtraction::subtract (float x, float y)
{     
  float dif;
  dif=x-y;
  return dif;    
}

multiplication.h

class Multiplication 
{
public:
  float multiply (float x, float y);
};

multiplication.cxx

#include "multiplication.h"

float Multiplication::multiply (float x, float y)
{
  float prod;
  prod=x*y;
  return prod;
}

and so on...

main.cxx

#include "subtraction.h"
#include "multiplication.h"

int main()
{
 //use the classes just as before.
}

Also, I didn't put it in the code here, for simplicity, but go ahead and get into the habit of ensuring that your declarations are only included once. On a large project, this can get very nasty if you don't put these safeguards in.

#ifndef SUBTRACTION_H
#define SUBTRACTION_H

class Subtraction
{
     ....
};
#endif /*SUBTRACTION_H*/
Jonathan Henson
  • 8,076
  • 3
  • 28
  • 52
  • wow thanks much!!! this clears a lot of things up! appreciate you taking the time to write this out for me. and also, I'm assuming ".cxx" is the same thing as ".cpp"? – Carpetfizz Aug 09 '12 at 14:04
  • @Carpetfizz, yes, you can use .cc, .cpp, .cxx, .c++, and some more, but those are the main extensions. – Jonathan Henson Aug 09 '12 at 14:05
  • Ok, so I tried the things you said for only one operation (Addition) and pretty much did exactly what you did. However, in my main, I deleted the Addition class (which was there before), since it has its own class now. However, CodeBlocks points to my "#include – Carpetfizz Aug 09 '12 at 14:14
  • @Carpetfizz it should be #include "Addition.h" not #include – Jonathan Henson Aug 09 '12 at 14:17
  • worked perfectly now! Thank you soo much Jonathan Henson! I also asked this question to stjin, is it possible to mark two answers as resolved? Both of you gave me a lot of knowledge and cleared up some stuff for me. – Carpetfizz Aug 09 '12 at 14:22
  • @Carpetfizz <> goes around system headers, "" goes around your custom headers. Regardless, do not mix < and " on the same #include directive. Also, I strongly recommend losing the "using namespace" directives and just use fully qualified type names. That will also cause problems in a large project, and be more difficult for others to read in a multiple file project. – Jonathan Henson Aug 09 '12 at 14:22
  • alright I will remember to do that, and yes, those symbols were what threw me off, since I have to repeat this process for a few more operations, I think I'll get the hang of it! – Carpetfizz Aug 09 '12 at 14:24
  • @Carpetfizz no, but its okay. You mark whatever helps you and what you think will steer future viewers of this post in the right direction. – Jonathan Henson Aug 09 '12 at 14:25
  • Ok, well since your answer was very easy to understand and was first, I marked it :) – Carpetfizz Aug 09 '12 at 14:37
2

here's something like Jonathan's example (I did not add the include guards for brevity, definitely do so though!), but with some duplication removed and some OO added for your learning pleasure. Note that while this is certainly not how an actual calculator would be implemented, it will hopefully give you some more understanding of C++ if you study it well enough.

mathoperation.h:

  //a base class!
class MathOperation
{
public:
  virtual float doit( float x, float y ) const = 0;
};

subrtaction.h:

class Subtraction : public MathOperation
{
public:
  float doit( float x, float y ) const;
};

addition.h:

class Addition : public MathOperation
{
public:
  float doit( float x, float y ) const;
};

subtraction.cpp:

#include "subtraction.h"
float Subtraction::doit( float x, float y ) const { return x - y; }

addition.cpp:

#include "addition.h"
float Subtraction::doit( float x, float y ) const { return x + y; }

main.cpp:

#include <iostream>
#include <string>
  //yes this saves typing, but there reasons not to use it.. search SO!
using namespace std;

  //this one avoids you having to copy/paste the similar parts
void DoIt( const MathOperation& op, const std::string& opName, const std::string& verb, const std::string& resultName )
{
  cout << "You have chosen " << opName << "!" << endl;

  cout<<"Enter the first number you want to " << verb << ": "<< endl;

    //here you should actually check if the user really types in a number, and not    "blablabla"
    //and off course, put it in a seperate function so you can reuse it for num2
  float num1;
  cin>>num1;

  float num2;
  cout<<"Enter the second number you wat to " << verb << ": "<< endl;
  cin>>num2;

  cout<<"The " << resultName << " is " << op.doit( num1, num2 ) <<endl;
}

int main()
{
int op;
char cont = 'n';

do {
  cout<<"Welcome to C++ Calculator v2!"<<endl;
  cout<<"Select the number for which operation you want to use: "<<endl;
  cout<<"1-Addition"<<endl;
  cout<<"2-Subtraction"<<endl;
  cout<<"3-Mutliplication"<<endl;
  cout<<"4-Division"<<endl;
  cin>>op;

    //see how much shorter this is?
  if( op == 1 )
    DoIt( Addition(), "Addition", "add", "sum" );
  else if (op==2)
    DoIt( Subtraction(), "Subtraction", "subtract", "difference" );
  else
    cout << "Sorry I don't know this number" << endl;

  cout<<"Do you wish to continue? Y/N"<<endl;
  cin>>cont;

} while (cont=='Y'||cont=='y');

cout<<"Thanks for using my program, goodbye!"<<endl;
return 0;
}
stijn
  • 34,664
  • 13
  • 111
  • 163
  • 1
    I think this is sound advice for a different question that is about design, Inheritance, or Polymorphism. Not sure if it helps here as it might confuse things. Anyhow, I like it and it is good advice. +1 – Jonathan Henson Aug 09 '12 at 14:19
  • thanks much stijn! this will be a great learning tool for me, is it possible for me to "check" multiple answers in SO? – Carpetfizz Aug 09 '12 at 14:20
  • no there can only be one answer. But by all means pick @JonathanHenson 's answer, not mine: he was first and answers exactly your question. I just added some advice and such because I'm somewhat bored and you seem eager to learn :] – stijn Aug 09 '12 at 14:25
  • Hey stijn, well thanks for making me feel better about not being able to choose both of you :) I hope you know that you gave me equally as much knowledge as John did, and will come back to your answer when I'm ready to learn a bit more advanced concepts about classes. Thanks again to both of you! – Carpetfizz Aug 09 '12 at 14:30
0

It's good to name your files the same way as the class. It's not such a good idea in your case, beacause your classes are short, but each class should have its own 2 files - for example Subtraction.h and Subtraction.cpp. In the .h file you should put only the decaration - in your case: class Subtraction { public: float subtract (float , float); }

In the .cpp file you should include the .h file and put the implementation. In your case:

float Substraction::subtract (float x, float y) { float dif; dif=x-y; return dif; }

See also C++ Header Files, Code Separation and Why have header files and .cpp files in C++?

Hope this helps a bit! :)

Community
  • 1
  • 1
Faery
  • 4,552
  • 10
  • 50
  • 92
  • hmm this makes things a lot clearer thanks! i'll try an implement this, and see where it takes me. – Carpetfizz Aug 09 '12 at 13:54
  • 1
    `float Substraction::subtract (float x, float y) { return x-y; } }` will do fine as well. Or at least, initialize the temporary immediately instead of first declaring it and then one line further assigning to it – stijn Aug 09 '12 at 13:55
0

It's good to have only one public class per file. By convention filename is the same as the classname (with an extension like .h .hh or .hpp if some definitions are done in the file).

if you want to put different classes in different files, a simple text editor will help you to do that.

N4553R
  • 188
  • 4
  • thanks for the tip, and how might I use a text editor for this? do you mean for copy and pasting? – Carpetfizz Aug 09 '12 at 13:55
  • theirs two main distinct things in an ide, editing, then for a compiled language compile, and execute code. For editing part, you may use any textEditor, from notepad to emacs (vi, np++, geny etc...). or an other ide... For compilation, use a separate compiler or the one in the ide... Personally i generally use makefiles or cmake and emacs for c++ (but it's really old fashion and I'm ide reluctant). – N4553R Aug 09 '12 at 14:01