I'm running an option pricing model that yields four values for four different options.
class EuroOption
{
private:
double S; //underlying stock price
double X; //strike price
double sigma; //volatility
double T; //time to expiration
double r; //risk-free rate
double b; //cost of carry
public:
EuroOption(); //default constructor
~EuroOption(); //destructor
EuroOption(const EuroOption& eo); //copy constructor
EuroOption& operator = (const EuroOption& source); //assignment operator
EuroOption(vector<double> Batch1);
EuroOption(vector<double> Batch2); //this is the error: redeclaration
//EuroOption(vector<double> const Batch3);
//EuroOption(vector<double> const Batch4);
Here is the source material from .cpp:
EuroOption::EuroOption(vector<double> Batch1) : S(60), X(65), sigma(0.30), r(0.08), T(0.25), b(r)
{
}
EuroOption::EuroOption(vector<double> Batch2) : S(100), X(100), sigma(0.20), r(0), T(1), b(r)
{
}
The errors I'm getting are "constructor cannot be redeclared". But my functions have different arguments(Batch1/Batch2) so I don't understand why it's not overloading. The output for Batch2 is also the same as Batch 1 (this is not correct). I'd be grateful for the guidance you may have.
The overloading is based on the parameter types not parameter names.
EuroOption::EuroOption(vector<double> Batch1)
Here vector<double> is the parameter type and Batch1 is the parameter name.
If you want overloading functions, you should declare functions with different parameter types or different number of parameters.
For eg, these are overloaded functions,
EuroOption::EuroOption(vector<double> Batch1)
EuroOption::EuroOption(vector<int> Batch1)
EuroOption::EuroOption(string Batch1)
I'm guessing the intent of what you want to do is to tag dispatch the constructor, or something similar, so that EuroOption is constructed with different hard-coded defaults.
struct Batch1{};
struct Batch2{};
class EuroOption
{
private:
double S; //underlying stock price
double X; //strike price
double sigma; //volatility
double T; //time to expiration
double r; //risk-free rate
double b; //cost of carry
public:
EuroOption(); //default constructor
~EuroOption(); //destructor
EuroOption(const EuroOption& eo); //copy constructor
EuroOption& operator = (const EuroOption& source); //assignment operator
EuroOption(Batch1);
EuroOption(Batch2);
.cpp file:
EuroOption::EuroOption(Batch1) : S(60), X(65), sigma(0.30), r(0.08), T(0.25), b(r)
{
}
EuroOption::EuroOption(Batch2) : S(100), X(100), sigma(0.20), r(0), T(1), b(r)
{
}
Then elsewhere in your code it could be constructed as:
EuroOption option1{Batch1{}};
EuroOption option2{Batch2{}};
These constructors are same:
EuroOption(vector<double> Batch1);
EuroOption(vector<double> Batch2);
These declarations are equivalent to:
EuroOption(vector<double>);
EuroOption(vector<double>);
It is because the function signature is the same. This is determined by the return type, name and number and type of the arguments.
Although the parameter name is different, the functions have exactly the same signature. In your example, when you call the constructor how do you decide which constructor gets called? The only difference is the parameter name but that is not accessible to the caller.
For future reference check: http://www.cplusplus.com/doc/tutorial/functions2/
Method Overloading means same method different signatures
EuroOption(vector Batch1);
EuroOption(vector Batch2);
same method has declared two times in the same class cause an error method redeclaration
Related
The error happen when I try to use one of my get function on parameter inside member functions. The error is:
Invalid arguments '. Candidates are : int getTotalArea() .
here is an example from my code :
class Apartment{
public : // ...
enum SquareType {EMPTY, WALL, NUM_SQUARE_TYPES};
bool operator<(const Apartment& apartment); // done - need help
int getTotalArea(); // done
private:
int price;
int length;
int width;
SquareType** squares;
};
int Apartment::getTotalArea()
{
int count=0;
for(int i=0;i<width;i++)
{
for(int j=0;j<length;j++)
{
if(squares[i][j]==EMPTY)
{
count++;
}
}
}
return count;
}
bool Apartment::operator<(const Apartment& apartment)
{
int thisArea=this->getTotalArea();
int paramArea=apartment.getTotalArea(); // the error line is here !!!
//the error is Invalid arguments '. Candidates are : int getTotalArea() .
double thisRatio=((double)price)/thisArea;
double paramRatio=((double)apartment.price)/paramArea;
if(thisRatio==paramRatio)
{
return price < apartment.price;
}
return thisRatio<paramRatio;
}
Have I done something wrong ?
It's the first time I'm using c++ ... by the way - any comments for the rest of the code are fine as well.
From the answer of PcAF seems you've heavily changed your initial post without modifying your question. Very bad!
However, the problem you're facing now with getTotalArea is that it isn't declared const.
See https://stackoverflow.com/a/751690/781933 for explanation.
Seems like you misunderstood operator overloading (as members)
When overloading some operator as member, then first operand of that operator is object on which member operator overload is called and second operand is parameter to that function (in case of binary operators).
operator + can be used as binary(2 operands) or unary operator(1 operand).
Here it seems like you want to overload binary version as member:
Apartment operator+(const Apartment& apartment1,const Apartment& apartment2);
but since first operand is object on which that member "function" is called it must take only 1 parameter (which is second operand).
Apartment operator+(const Apartment& apartment2);
Here is the second mistake:
Apartment& operator=(SquareType** squares, int length, int width, int price);
operator = is binary operator (2 operands), therefore if you want to overload it as member function it has to take exactly one parameter (which is second operand of =), not 4 parameters.
I have a take home test that it work a large percentage of my grade. These 3 questions are on it and they are worth half the test. I was wondering if someone could kindly review my quiz and make sure they are correct for me. I’m a worrier and I want to make sure they are correct. Thank you in advance!
Implement the constructor for the class called "SimpleMath". The constructor takes two integer parameters; "var1" and "var2". The constructor is to store the value that was passed into "var1" into the private integer member variable "m_value1" and the value that was passed into "var2" into the private integer member variable "m_value2"
class SimpleMath
{
public:
SimpleMath(int var1, int var2) : m_value1(var1), m_value2(var2) {};
int getVar1() const
{
return m_value1;
}
int getVar2() const
{
return m_value2;
}
private:
int m_value1;
int m_value2;
};
Implement the "Multiply" method for the "SimpleMath" class. This method does not require any parameters and returns an integer value. This method should multiply the values stored in the classes private integer member variables "m_value1" and "m_value2" the resulting value is returned. Assume that "m_value1" and "m_value2" were loaded inside the classes constructor.
class SimpleMath
{
public:
SimpleMath(int var1, int var2);
int Mutiply= m_value1* m_value2;
private:
int m_value1;
int m_value2;
};
Write a class definition called "SimpleMath" that has a constructor that takes two integers "var1" and "var2". It has four public methods that take no parameters and return an integer value; "Add","Subract","Divide" and "Multiply". The class has two private member variables of type integer; "m_value1" and "m_value2".
class SimpleMath
{
SimpleMath(int var1, int var2);
public:
int Add;
int Subract;
int Divide;
int Multiply;
private:
int m_value1;
int m_value2;
};
Am I to assume you have no prior programming experience?
At any rate, the first part looks ok. What the : denotes is the initializer list. It can, and is, correctly used to initialize a class's members.
Second part, you got it dead wrong I am afraid.
First of, you've not implemented the method Multiply() there, you've just declared a variable.
Instead do this:
int Multiply()
{
int sum = m_value1 * m_value2;
return sum;
}
For brevity's sake, you can also do this:
int Multiply()
{
return m_value1 * m_value2;
}
Does the same thing.
Also note that the answer from question 1 has not carried over to question 2, ie the constructor is incomplete. It won't compile.
As for question 3, it's just question 2 all over again, except you've also got to implemented the three remaining arithmetic functions. Suffice it to say, I am sure you can figure it out.
I'm sorry if this has been asked already, but I'm still learning C++ and struggling with a bit of syntax.
I'm supposed to overload the type conversion operator, so that it will accept an object and return an int value, based on a protected int inside that object.
Header file:
definitions.h
class Baseballs
{
protected:
int currentValue;
public:
Baseballs(int);
int operator= (Baseballs&); // ??????
}
Methods:
methods.cpp
#include "definitions.h"
Baseballs::Baseballs(int value)
{
currentValue = value;
}
int Baseballs::operator=(Baseballs &obj) // ??????
{
int temp = obj.currentValue;
return temp;
}
So in main.cpp, if I create an object:
Baseballs order(500);
Then 500 is assigned to currentValue. I need to be able to assign that to an int variable, and ultimately print it for verification, such as:
int n = order;
cout << n;
What I'm having trouble with is the syntax for overloading =. Can someone tell me what the proper syntax for the definition and method should be?
The overloaded = is really to assign to objects of the same type. Ex:
order = another_order;
What you are looking for is an overloaded conversion operator.
operator int() { return currentvalue; }
However this is generally not regarded as good practice, due to unknown conversions. An explicit overload is much safer:
explicit operator int() {...}
However you would need to do:
int n = static_cast<int>(order);
I'll try to make this as concise as possible and while I understand that these questions can be considered "basic" I have already looked at websites such as cplusplus.com and yolinux tutorials but i need somebody to explain this to me like I have just had a major head trauma..
1)
class Rectangle {
private:
int lineNumber; // LineNumber of the ACSIL Tool
float valueMax; // value of the higher limit of the rectangle
float valueMin; // value of the lower limit of the rectangle
public:
Rectangle(SCStudyInterfaceRef sc, int lineNumber, float valueMax, float valueMin);
int getLineNumber();
float getValueMax();
float getValueMin();
};
So int linenumber, valueMax and ValueMin are declared private members and thus are only accessible by members of the same class, thats fine. But what about the part that follows the "public:" ?
a) Is Rectangle(SCStudyInterfaceRef sc, int lineNumber, float valueMax, float valueMin); a function that is being overloaded? and if yes are int getLineNumber() etc part of that function or seperate members of the public part of the class?
2)
Rectangle::Rectangle(SCStudyInterfaceRef sc, int lineNumber0, float value1, float value2) {
lineNumber = lineNumber0;
int value2_greater_than_value1 = sc.FormattedEvaluate(value2, sc.BaseGraphValueFormat, GREATER_OPERATOR, value1, sc.BaseGraphValueFormat);
if (value2_greater_than_value1 == 1) {
valueMax = value2;
valueMin = value1;
} else {
valueMax = value1;
valueMin = value2;
}
}
int Rectangle::getLineNumber() {
return lineNumber;
}
float Rectangle::getValueMax() {
return valueMax;
}
float Rectangle::getValueMin() {
return valueMin;
}
a) I'm pretty sure that the functions defined inside the public part of the rectangle class are being "defined" here, or something along those lines.
b) I am really confused about what is happening here on the Rectangle::Rectangle(SCStudyInterfaceRef sc, int linenumber0, float value1, float value2) part. I understand the logic of what is happening within the function itself but i am confused about the paramters being input within the " ( ) " and how exactly this relates to what happenes inside the class public part. This really is the most important question that needs answering.
I have tried to be as concise and onpoint as possible, would appreciate some help in understanding this syntax.
Question 1
It's a constructor with 4 parameters.
int getLineNumber();
float getValueMax();
float getValueMin();
are all member functions in the class.
Question 2
The constructor defined earlier is called with 4 parameters. If no other constructor is defined then you'll have to instantiate the class with exactly 4 parameters, i.e:
Rectangle *rect = new Rectangle(sc, 100, 1.2, 6.8);
or simply:
Rectangle rect(sc, 100, 1.2, 6.8);
These parameteres are then used to "set the object in an initial state".
The member functions are used to get various values in their current (or final or only) state.
Rectangle::Rectangle is the class constructor. It is called whenever a Rectangle object is created. Read about constructors to understand better.
The constructor is setting initial values for the valueMax and valueMin member variables. It uses the parameters passed to the constructor to do this. Read about function parameters to understand better.
1) a: If no ctor function is declared, then the compiler writes a ctor for the class. But when a ctor is provided by the class no default ctor is written by the class and hence no overloading is taking place. Now if you go on and define one more ctor, may be because you want the object to be constructed in some other way, then you will have an overloaded ctor. In your case no overloading is taking place.
int getLineNumber() is just another member of the class.
2)
a: You are correct.
b: The parameters put inside "( )" are arguments list and if this function is called somewhere, then this list is type-matched and then function is called(in case of overloading). Now if you write a statement like:
Rectangle x(a, b, c, d);
then it means that your sc=a, lineNumber0=b, value1=c, value2=d for this function call.
I'm trying to instantiate a few classes, with references to the first class passed along.
The compiler gives me an error stating: error: 'classData' is not a type.
ClassData hold some complicated data structures and has a bunch of accessors to that data. ClassFunc has a bunch of functions that operate on that data. Then the Work class does a bunch of work and occasionally needs to call a function in ClassB that will do some work on the data in ClassData.
Below is the code:
/////////////////////////
//ClassData.h
class ClassData {
public:
ClassData(){
// initialize a bunch of stuff
};
virtual ~ClassData(){};
}
/////////////////////////
//ClassFunc.h
#include "ClassData.h"
class ClassFunc {
public:
ClassFunc(ClassData& in_classData) : classData(in_classData){};
virtual ~ClassFunc();
float updateEta(float deltaVJ, int column);
private:
ClassData& classData;
};
/////////////////////////
//ClassFunc.cpp
#include "ClassFunc.h"
float ClassFunc::updateEta(float a, int b){
float foo = 0.0
// Do a bunch of work to foo
return foo;
};
/////////////////////////
// Work.h
#include "ClassData.h"
#include "ClassFunc.h"
class Work{
public:
Work(ClassData& in_class) : classData(in_class){
// initialize some stuff
};
~Work(){};
float updateTheta(int a, float b, float c);
private:
ClassData& classData;
ClassFunc classFunc(classData); //// ERROR IS HERE
}
/////////////////////////
// Work.cpp
#include "Work.h"
float Work::updateTheta(int a, float b, float c){
// do some work first
double foo = classFunc.updateEta(d, e);
return foo
};
Your compiler's right: classA isn't a type. C++ is case-sensitive; ClassA is the type you're looking for (check the first line of ClassB's constructor).
Hope that helps!
Answer After question modification
ClassFunc classFunc(classData); is not valid syntax in the definition of a class. You will need to have this classFunc variable by either a set function or through the constructor.
However, writing just a setter will be difficult because your ClassFunc requires a ClassData. In order to work around this, you may need to modify your ClassFunc also.
Also, there is another error. ClassData and Work are missing a ; at the end of its definition.
Original Answer before question modification
There are several errors in this code. Such as
float ClassA::funcA{
Should be
float ClassA::funcA(){
As other wise, it looks like a function definition.
Second, there is
ClassB(Class A& in_classA): classA(in_classA){
As it should be
ClassB(ClassA& in_classA): classA(in_classA){
As Class A is not a type.
Also, you are missing several semicolons but those should be obvious to spot.
The problem is that you cannot initialize member variables in the class declaration:
ClassFunc classFunc(classData);
Instead, initialize it in the initializer list of the constructor:
Work(ClassData& in_class) : classData(in_class), classFunc(classData) {}