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.

9
  • 1
    too much words, please, edit your post for better reading Commented Aug 9, 2012 at 13:43
  • ugh sorrry, for some reason I can't get the numbered lists to work, any idea how? Commented Aug 9, 2012 at 13:43
  • 1
    You need to seperate into declaration (.h) files and implementaion (.cpp) files. Commented Aug 9, 2012 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. Commented Aug 9, 2012 at 13:45
  • see edit for numbered lists: you need an extra newline before them Commented Aug 9, 2012 at 13:46

4 Answers 4

9

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*/
Sign up to request clarification or add additional context in comments.

9 Comments

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, yes, you can use .cc, .cpp, .cxx, .c++, and some more, but those are the main extensions.
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 <Addition.h" and gives me a "no such file or directory" error. I double checked spelling and there are no other projects open. Do you know what could have made it do this? Also, I included "iostream" in the .cpp file of my addition class since it didn't have one. About the declarations, CodeBlocks already wrote those out for me.
@Carpetfizz it should be #include "Addition.h" not #include <Addition.h". Also, the compiler is probably case sensitive so you will want to make sure you have everything capitalized correctly.
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.
|
3

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;
}

4 Comments

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
thanks much stijn! this will be a great learning tool for me, is it possible for me to "check" multiple answers in SO?
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 :]
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!
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! :)

2 Comments

hmm this makes things a lot clearer thanks! i'll try an implement this, and see where it takes me.
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
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.

2 Comments

thanks for the tip, and how might I use a text editor for this? do you mean for copy and pasting?
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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.