Separate classes into separate files in C++ - c++

EDIT: Added the "addition" class in, accidentally forgot about it.
How do I separate classes into different files? I understand how classes work and how to make objects and things like that. However, I'm finding some confusion in the process of putting classes in different files. Thanks much for any help! Also, I am using CodeBlocks as an IDE. Here is my understanding so far:
Create new class, and CB gives you a ".h" and a new ".cpp".
The "Classname::Classname" at the beginning of the source file is a Scope Resolution Operator.
You use "#include classname.h" in your main source file to import its contents.
You can call functions from "main" by using the objects that you have declared.
This is my understanding so far, but I'm just confused on how to implement it. I have created a simple calculator with all the classes in one source file. It works fine, and I guess I'm pretty proud of it :) I know there is a lot easier way to make something like this, but I used classes and objects instead for the sole purpose of practice. Here's my code for the calculator. Also, I really apologize for the long post :/ Thanks, if you have come this far in reading it, and thanks especially if you can help me out a bit!
Here's my code 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;
}

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*/

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

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! :)

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.

Related

How to use Complex numbers in Class/Object C++

Im strugling to implement complex numbers into my code. When I compile it gives me random numbers. It should use imaginary number i = sqrt(-1). It should output realPart + imaginaryPart * i.
#include <iostream>
#include <complex>
using namespace std;
class Complex
{
private:
double i;
complex<double> imaginarypart = i*sqrt(1);
double realpart;
public:
void seti(double a1) {
i = a1;
}
void setrealpart(double a2) {
realpart = a2;
}
void printwhole() {
cout << realpart + imaginarypart;
}
};
int main()
{
double a, b;
cout << "Enter your realpart" << endl;
cin >> a;
cout << "Enter your imaginarypart " << endl;
cin >> b;
Complex num1;
num1.seti(b);
num1.setrealpart(a);
cout << endl;
num1.printwhole();
}
The point is that an the type double cannot store imaginary values.
Yet you try to do so, e.g. with sqrt(1); (though you probably meant -1).
The complex<double> is indeed able to store imaginary values, but on the one hand it won't work by assigning the product of the non-initialised i with 1 and on the other hand you seem to try to implement complex numbers yourself. Using the provided complex standard type somewhat defeats that. If you use it, then you just need to learn outputting it in the format you want, instead of doing all the implementation work.
Lets assume that you are more interested in getting it done yourself first.
What you need to do is to always represent complex numbers as two numbers.
I hence propose to change your code likes this.
#include <iostream>
using namespace std;
class Complex
{
private:
/* double i; Won't work, it cannot store imaginary values. */
double imaginarypart;
double realpart;
public:
void setimaginarypart(double a1) {
imaginarypart = a1;
}
void setrealpart(double a2) {
realpart = a2;
}
void printwhole() {
cout << realpart << '+' << imaginarypart << 'i'; // To get the output you want.
}
};
int main()
{
double a, b;
cout << "Enter your realpart" << endl;
cin >> a;
cout << "Enter your imaginarypart " << endl;
cin >> b;
Complex num1;
num1.setimaginarypart(b);
num1.setrealpart(a);
cout << endl;
num1.printwhole();
}
Alternatively use existing solutions (e.g. std::complex), instead of trying to program one yourself. Outputting them in the shape you want (r+i*I) does not require to implement the whole thing yourself.
Have a look at https://en.cppreference.com/w/cpp/numeric/complex to learn about what it offers.
As you figured out, complex numbers have a real and an imaginary part. And in std::complex<double>, those two parts are combined.
But in your class Complex, you have Complex::i, Complex::realpart, Complex::imaginarypart::real() and Complex::imaginarypart::imag(). That's 4 parts!
Furthermore, complex<double> imaginarypart = i*sqrt(1); means that Complex::imaginarypart is set to i*sqrt(1) when a Complex object is created. But at that time, i is still uninitialized! So that won't work either. This is why you get random numbers (or a crash, depending on your luck).
The simple solution is to drop your whole class Complex. std::complex<double> already has functions to set the real and imaginary parts, namely std::complex<double>::real(double) and std::complex<double>::imag(double)
(Note: real and imag are setters if you pass a value, getters if you don't).

Difficulty with Calling Functions from Separate Source Files in Visual C++ **UPDATE**

I really hope this falls within guidelines, but I have a potential silly question: I'm trying to get a good feel of how multiple header and source files fit together in a C++ program. To do so, I'm making a calculator for simple physical formulae.
#include "stdafx.h"
#include "rotationalKinematics.h"
#include "Kinematics.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
//declare local variables:
int fieldChoice = 0;
//query field of equations:
cout << "What physical properties would you like to solve for?\n (1) kinematics\n (2) rotational kinematics\n Please enter number: ";
cin >> fieldChoice;
if (fieldChoice == 1) {
int mainKinematics();
return 0;
}
if (fieldChoice == 2) {
int mainRotationalKinematics();
return 0;
}
return 0;
}
The program compiles without error, and the two functions mainKinematics() and mainRotationalKinematics() are defined and declared in separate .cpp and .h files, respectively. For example, I've included the a header and a source file for mainKinematics() below:
#include "stdafx.h"
#include "Kinematics.h"
#include <iostream>
#include <cmath>
using namespace std;
//function declaration:
double kinDeltaX_acceleration(double velocityInitial, double deltaTime, double acceleration);
int mainKinematics()
{
//local variable declaration:
double velocityInitial = 0;
double velocityFinal = 0;
double velocityFinalSquared = 0;
double acceleration = 0;
double deltaX = 0;
double deltaTime = 0;
int solveFor = 0;
//query variable to solve for:
cout << "What variable would you like to solve for?\n (1) DeltaX w.r.t. acceleration\n (2) DeltaX w.r.t. velocity\n (3) Final velocity\n (4) Final velocity squared\n Please enter number: ";
cin >> solveFor;
//query for values based on solveFor choice:
if (solveFor == 1) {
cout << "Please enter value for velocityInitial: ";
cin >> velocityInitial;
cout << "Please enter value for deltaTime: ";
cin >> deltaTime;
cout << "Please enter value for acceleration: ";
cin >> acceleration;
//function call:
deltaX = kinDeltaX_acceleration(velocityInitial, deltaTime, acceleration);
cout << deltaX;
}
if (solveFor != 1 && solveFor != 2 && solveFor != 3 && solveFor != 4)
{
return 0;
}
return 0;
}
//functions:
double kinDeltaX_acceleration(double velocityInitial, double deltaTime, double acceleration)
{
//local variable declaration:
double result;
result = velocityInitial*deltaTime + .5 * acceleration * pow(deltaTime, 2);
cin.clear();
cin.sync();
cin.get();
return result;
}
and the related Kinematics.h header file:
#ifndef Kinematics
#define Kinematics
#pragma once
//function declarations:
double kinDeltaX_acceleration(double velocityInitial, double deltaTime, double acceleration);
double kinDeltaX_velocity(double velocityInitial, double velocityFinal, double deltaTime);
double kinVelocityFinal(double velocityInitial, double acceleration, double deltaTime);
double kinVelocityFinalSquared(double velocityInitial, double acceleration, double deltaX);
int mainKinematics();
#endif
When I solely compiled the Kinematics.cpp file (above) it worked fine. However, when I tried to tie the Kinematics.cpp file and the rotKinematics.cpp files together into one overarching main file (shown in the first code example) I run into the following problem: the code compiles without error, it takes user input for which function to access, and then immediately closes without seeming to execute the called function from a separate source file. Am I doing something wrong in the way I'm calling the functions?
Any help is appreciated immensely and thank you for your time!!
P.S. I realize that I declare the functions in both the .cpp and .h files; when I do not include the declaration in the .cpp file the compiler returns errors. This suggests that I'm doing something wrong, though I haven't been able to figure out what.
UPDATE
Hello! Thank you all so much for weighing in on this! With the resources provided I've found a workaround as such:
if (fieldChoice == 1) {
int val = -1;
val = mainKinematics();
return 0;
Referencing the function in my original script wasn't actually returning anything; by creating an intermediate object (val) to hold the final value the script now seems to work as intended. What do you folks think? Is this an okay solution?

Having trouble calling two variables from method into main C++

I am having trouble with a very simple program. I need to call in a method (getNumber) outside of main that takes two numbers from the user and then store those numbers. Those two numbers are then used in a calculation method (math) which is also called into main. I am getting an uninitialized local variable for my two numbers I am calling in from getNumber. I would like the user to enter two numbers have them added together and display the result but by calling in methods.
#include <iostream>
#include <string>
using namespace std;
int getNumber(int x, int y)
{
// here is where the user is prompted to input two numbers
cout << "Please enter two values" << endl;
cin >> x >> y;
return x, y;
}
int math(int x , int y) // here is where the calculations are done
{
int result;
result = x + y;
return result;
}
int main()
{
int x;
int y;
int result;
x = getNumber(x, y); // trying to call in the input method here
result=math(x,y); // calling in claculation method
cout << result;
system("pause");
return 0;
}
void getNumber(int &x, int &y)
{
cout << "Please enter two values" << endl;
cin >> x >> y;
}

Expression Must Have Class Type (Using a struct array as a function parameter)

I am writing a C++ program in Visual Studio Pro 2013, and I am having an error when trying to use a structure array as a parameter in a function call. This is my code.
struct ProcessingData
{
double latitude;
double longitude;
};
double distanceCalculator(double dataLat[], double dataLong[], double inLat, double inLong)
{
//some code in here
}
int main()
{
char userChoice;
double userLatitude;
double userLongitude;
ProcessingData dataInfo[834];
cout << "Welcome!\n"
<< "Please select which option you would like to run:\n\n"
<< "A) Calculate the distance from a specified set of coordinates.\n"
<< "B) Print out the information for all waypoints.\n\n"
<< "Please enter your selection now: ";
cin >> userChoice;
switch (userChoice)
{
case 'a': //Menu option for distance calculation
{
getTheFile(); //other function that is being used
cout << "Please enter the latitude for the coordinate you are using: ";
cin >> userLatitude;
cout << "Please enter the longitude for the coordinate you are using: ";
cin >> userLongitude;
distanceCalculator(dataInfo.latitude[], dataInfo.longitude, userLatitude, userLongitude)
}
break;
I am getting an error in my distanceCalculator function call, on the dataInfo.latitude and dataInfo.longitude that says "expression must have class type."
Why am I getting this error and how to I solve it?
The variable dataInfo is an array of ProcessingData. The class ProcessingData has a member latitude.
You seem to want to deal with an array consisting of the latitude members of the elements of dataInfo, but no such array exists. You can take a member of a struct, but you can't use the same syntax to extract that member from all elements of the array in one step.
If you want to pass an array, you have a couple of options. Passing the array is easy:
void foo(int A[])
{
...
}
int A[8];
foo(A);
The trouble is that the function has difficulty knowing the size of the array, so it is easy to go out of bounds. We can add another parameter for the size of the array:
void foo(int A[], unsigned int nA)
{
...
}
int A[8];
foo(A, 8);
or start using the standard containers:
void foo(vector<int> A)
{
...
}
vector<int> A;
foo(A);
Each instance of a ProcessingData contains one double for Latitude and one double for Longitude.
There are no arrays of double here. It seems as if you are trying to automagically "view" an array of double by selecting all the Latitude doubles from dataInfo, however it doesn't work that way.
Your simplest solution will probably be to change the function to be:
double distanceCalculator(ProcessingData data[], double inLat, double inLong)
{
// logic here using things like data[5].latitude
}

c++ class passing member function issues

In class were learning about classes and structures, Im working on a program that is supposed to have to member functions in the class, one doing calculations and one to return certain values, it seems Im running into trouble calling the functions maybe? IM not a 100% sure because c++ cant specify the error. I hope you can help me, thank you in advance.
#include <iostream>
#include <cstdlib>
using namespace std;
void rocket(double massR,double massE, double massP,double avgTh,double bd);
double rocketreturn(double& MV,double& MA);
class Rocket
{
private:
double massR;
double massE;
double massP;
double avgTh; // average thrust
double bd; //burn duration
public:
void rocket(double massR,double massE, double massP,double avgTh,double bd)
{
massR=massR/1000;
massE=massE/1000;
massP=massP/1000;
double LM=massR+massE;
double MCP=massR+massE-massP;
double AM=(LM+MCP)/2;
double acc=(avgTh/AM)-9.8;
double MV= acc * bd;
double Alt=.5*acc*.5*.5;
double t=MV/9.8;
double MA=Alt+MV*t+.5*-9.8*t*t;
}
double rocketreturn(double& MV, double& MA)
{
cout<< MV;
cout<< MA;
}
};
int main( )
{
double massR; // mass of the rocket
double massE; // mass of the engine
double massP; // mass of the propellant
double avgTh; // average thrust
double bd; // burn duration
double MV; // max velocity
double MA; // max altitude
char ans;
system("CLS");
cout << "Take Home # by - "
<< "Rocket Object\n\n";
do
{
cout <<"Enter the mass of the rocket: "<<endl;
cin >> massR;
cout <<"Enter the mass of the engine: "<<endl;
cin >> massE;
cout <<"Enter the mass of the propellant: "<<endl;
cin >> massP;
cout <<"Enter the average thrust of the engine: "<<endl;
cin >> avgTh;
cout <<"Enter the burn duration of the engine: "<<endl;
cin >> bd;
rocketreturn(MV,MA);
cout <<"the rockets maximum velocity is " << MV<<endl;
cout <<"the rockets maximum altitude is "<<MA<<endl;
cout <<"Would you like to run the program again (Y or N)?"<<endl;
cin>>ans;
}
while(ans=='y'||ans=='Y');
}
You can try using the following program structure and fill in the details the way you wish. Note, it won't compile.
#include <iostream>
using namespace std;
class Rocket {
private:
double mR, mE;
public:
/* Constructor. It is missing in your program. You probably want it */
Rocket(double massR, double massE) {
/* Better to use initialization list, but this should work too */
mR = massR;
mE = massE;
}
double rocketreturn(double & a, double & b) {
/* Do sth with the parameters. But return a double,
which you are not doing in your program */
double result = a + b;
return result;
}
};
int main() {
double x, y;
do {
cin >> x >> y;
Rocket my_rocket(x, y);
double z = my_rocket.rocketreturn(x, y); // Assignment not necessary
} while ( /* some condition */) //my_rocket object will be destroyed after scope goes out
return 0;
}