Passing overloaded constructor to function between classes - c++

I have to put overloaded constructor form class Parameters into a function in class Solver.
Here is Parameters Header:
#ifndef Parameters
#define Parameters
#include <iostream>
#include<conio.h>
#include<fstream>
#include<string>
using namespace std;
class Parameters
{
int M;
double dx;
double eps;
public:
Parameters( );
Parameters(int M1, double dx1, double eps1 );
Parameters( string fileName);
};
#endif
The constructor initializes M, dx, eps with default values or chosen by the user from the keyboard or from the file.
I want to have another class which will be containing this initialized values (in order to solve some equation lately, also in this class).
The problem is that although I tried to do this by value, reference or/ pointers, there was always some error or code compiled but done nothing.
Here's my Solver class:
#include "ParametersH.h"
#include "EquationH.h"
#include <iostream>
#include<conio.h>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
class Solver
{
public:
int Solve( Parameters& obj );
};
int Solver::Solve( Parameters& obj)
{
cout << obj.M; // M is private so it fails :<
// another attempt was like this:
Parameters *pointer = new Parameters();
}
int main()
{
Solver Solve();
return( 0 );
}
I really couldn't handle this, hope someone will help.

As #lubgr mentioned in the comments, here
Solver Solve();
you declare a function named Solve() without parameters that give you a Solver object, not the member function Solve( Parameters& obj );
If your goal is to access private members of class Parameters in class Solver: You can either
define Solver a friend of Parameters: See here or
access through setters and getters or
make a struct of Parameters by which you can access everything inside
it
However, it looks like you only need a struct Parameters and a simple function Solve( Parameters& obj);, which will do your job.
struct Parameters
{
int m_;
double dx_, eps_;
Parameters(int M1, double dx1, double eps)
: m_(M1), dx_(dx1), eps_(eps) // provide other contrs as per
{}
};
int Solve(Parameters& obj)
{
std::cout << obj.m_ << " " << obj.dx_ << " " << obj.eps_ << std::endl;
return obj.m_;
}
now in the main() simply:
std::cout << "result: " << Solve(Parameters(1, 2.0, 3.0));

Related

Using a user defined class vector inside the class file

I have a class called Account with below parameters:
Account::Account(string ibanCode, string paramOwner, double amount) {}
I have created a vector consisting of class Accounts inside main function:
accs.push_back(Account(fullName, iban, value));
I want to write a function to print all the Account values in my vector by a class member function called displayAll() , and so far I tried this:
void Account::displayAll()
{
for (int i = 0; i < accs.size(); i++)
{
cout << accs[i].displayBalance() << endl;;
}
}
And I want to write it inside the class file. Do you have any suggestions?
I think making it a member would be extremely complicated, the best option should be using a normal function that can access the parameters.
#include <iostream>
#include <vector>
using namespace std;
struct Account {
Account (string ibanCode, string paramOwner, double amount) : _amount(amount), _ibanCode(ibanCode), _paramOwner(paramOwner) {};
string _ibanCode;
string _paramOwner;
double _amount;
};
void DisplayAll (const vector<Account>& Accs) {
for (const auto& Acc : Accs) {
cout << Acc._ibanCode<<' '<<Acc._paramOwner<<' '<< Acc._amount<<'\n';
}
return;
}
int main () {
vector<Account> Accs;
Accs.push_back(Account("SomeCode", "SomeOwner", 2.0));
Accs.push_back(Account("SomeOtherCode", "SomeOtherOwner", 3000.42));
DisplayAll(Accs);
}
To avoid complicating the answer too much I made a struct but you can either make the DisplayAll function a friend of the class or make some getters.

Virtual function with unkown parameter vector type

I am trying to build an optimization library in C++ for parameters optimization.
The problem and the parameters type may vary, e.g. if the problem is to minimize the Ackley Function, then we have a vector<double> of size 2 (index 0 for the x, and index 1 for the y). However, we may have problems where the parameters are integers, or even strings.
Many algorithm exist for this type of optimization, like Genetic Algorithm, Differential Evolution, etc. In most of them, once we modify the parameters based on their optimization strategy, we have to call an evaluation function that receives the parameters, and given a objective function, will return a value (fitness).
My question is how could I implement an abstract class Problem in C++ such that it contains an virtual double evaluate function in which receives as reference a vector of the generic type of the related problem? For example, user's problem should inherit Problem and he needs to specify a type T, in this case, the evaluation function should be like virtual double evaluate(const vector<T> &parameters){}.
If the strategy which I mentioned above is not feasible for C++. Please, suggest alternatives strategies.
Based on #Quentin comment and your details I would say that you could first declare Problem as a class template
#include <vector>
#include <typeinfo>
#include <iostream>
using namespace std;
template<class T>
class Problem
{
public:
Problem() {
if(typeid(T) == typeid(double)){
cout << "The problem is of type double" << endl;
}
}
virtual double evaluate(const vector<T> &decisionVariables) = 0;
};
Then you can inherit from it and override the evaluate function based on your needs. Since you mentioned Ackley Function, I implemented an AckleyFunction which inherits from Problem with type double
#include "problem.h"
#include "math.h"
using namespace std;
class AckleyFunction : public Problem<double>
{
public:
AckleyFunction() {}
double evaluate(const vector<double> &decisionVariables) override {
const double x = decisionVariables[0];
const double y = decisionVariables[1];
return -20 * exp(-0.2 * sqrt(0.5 * (pow(x, 2) + pow(y, 2)))) - exp(0.5 * (cos(2 * M_PI * x) + cos(2 * M_PI * y))) + exp(1) + 20;
}
};
The global minimum for the Ackley function is x = 0, and y = 0. You can see that bellow in the main.cpp
#include <ackleyfunction.h>
#include <memory>
using namespace std;
int main(int argc, char *argv[])
{
shared_ptr<Problem<double>> prob(new AckleyFunction());
vector<double> decisionVariables = {5.1, 3.3};
cout << "Value at coordinates (5.1, 3.3): " << prob->evaluate(decisionVariables) << endl;
decisionVariables = {0., 0.};
cout << "Value at coordinates (0.0, 0.0): " << prob->evaluate(decisionVariables) << endl;
}
Output:
The problem is of type double
Value at coordinates (5.1, 3.3): 12.9631
Value at coordinates (0.0, 0.0): 0
Would something like this do?
#include <memory>
#include <iostream>
#include <vector>
class Problem {
public:
virtual double evaluate() = 0;
};
class MyProblem : public Problem {
public:
MyProblem(const std::vector<float>& parameters) : mParameters(parameters) {}
double evaluate() override {
// Do evaluation based on mParameters
return 47.11;
}
private:
const std::vector<float>& mParameters;
};
int main() {
std::vector<float> v = {1.0f, 2.0f};
std::unique_ptr<Problem> p{new MyProblem(v)};
std::cout << p->evaluate() << '\n'; // Calls MyProblem::evaluate()
return 0;
}

Access variable from another class (in C++)

This may be a really easy question but... here it goes. (Thanks in advance!)
I am simplifying the code so it is understandable. I want to use a variable calculated inside another class without running everything again.
source.ccp
#include <iostream>
#include "begin.h"
#include "calculation.h"
using namespace std;
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply();
system("pause");
exit(1);
}
begin.h
#include <iostream>
using namespace std;
#ifndef BEGIN_H
#define BEGIN_H
class beginclass
{
public:
void collectdata();
int test;
};
#endif
begin.cpp
#include <iostream>
#include "begin.h"
void beginclass::collectdata()
{
test = 6;
}
calculation.h
#include <iostream>
#include "begin.h"
#ifndef CALCULATION_H
#define CALCULATION_H
class calculationclass
{
public:
void multiply();
};
#endif
calculation.cpp
#include <iostream>
#include "begin.h"
#include "calculation.h"
void calculationclass::multiply()
{
beginclass BEGINOBJECT;
// BEGINOBJECT.collectdata(); // If I uncomment this it works...
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}
Simply define member function multiply as
void calculationclass::multiply( const beginclass &BEGINOBJECT ) const
{
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}
And call it as
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply( BEGINOBJECT );
system("pause");
exit(1);
}
In your code beginclass has no explicit constructor, hence the implicitly defined default constructor will be used, which default constructs all members. Hence, after construction beginclass::test is either 0 or uninitiliased.
What you appear to be wanting is to avoid to call beginclass::collectdata() more than once. For this you would want to set a flag that remembers if beginclass::collectdata() has been called. The member function which returns the data then first checks this flags and, if the flag was not set, calls beginclass::collectdata() first. See also the answer by CashCow.
It looks like you are looking for some kind of lazy evaluation / caching technique whereby a value is calculated the first time it is requested then stored to return it subsequently without having to reevaluate.
In a multi-threaded environment the way to achieve this (using the new standard thread library) is by using std::call_once
If you are in a single-threaded environment, and you just want to get a value out of a class, use a getter for that value. If it isn't calculated in a "lazy" fashion, i.e. the class calculates it instantly, you can put that logic in the class's constructor.
For a "calc_once" example:
class calculation_class
{
std::once_flag flag;
double value;
void do_multiply();
double multiply();
public:
double multiply()
{
std::call_once( flag, do_multiply, this );
return value;
}
};
If you want multiply to be const, you'll need to make do_multiply also const and value and flag mutable.

Compiler Error - Identifier undefined

I have a fairly simple C++ code that doesn't seem to be compiling properly. Essentially, I have some globally defined functions declared in my GLOBAL.HPP file, and are defined in my GLOBAL.CPP file. Then I have a class, EuroOption, that consists of a struct datamember. The class EuroOption has its own member functions that essentially do the same exact thing that the global functions do--so I defined them similarly, and just called global functions inside of the EuroOption member function definitions. Please see below:
//
//GLOBAL.HPP
//
#ifndef GLOBAL_HPP
#define GLOBAL_HPP
#include <iostream>
#include <math.h>
#include <boost/math/distributions/normal.hpp>
#include <boost/math/distributions.hpp> // For non-member functions of distributions
using namespace std;
//using namespace boost::math;
namespace GLOBAL // Encapsulate Point in the Global namespace
{
struct EuroOptionData
{
double r; // Interest rate
double sig; // Volatility
double K; // Strike price
double T; // Expiry date
double b; // Cost of carry
};
double n(double x);
double N(double x);
double CallPrice(EuroOptionData od, double S);
double PutPrice(EuroOptionData od, double S);
double PutParity(EuroOptionData od, double S);
double CallParity (EuroOptionData od, double S);
} // Close namespace GLOBAL
#endif
Here is the EuroOption.HPP file:
//
//
//
#ifndef EUROOPTION_HPP
#define EUROOPTION_HPP
#include <string>
#include "Global.hpp"
using namespace std;
using namespace GLOBAL;
class EuroOption
{
private:
public:
struct EuroOptionData od;
//EuroOption class functions
EuroOption(); // Default call option
EuroOption(const EuroOption& option2); // Copy constructor
virtual ~EuroOption(); //Destructor
//EuroOption Global Function Calls
double EuroCallPrice(EuroOptionData od, double S);
double EuroPutPrice(EuroOptionData od, double S);
double EuroCallParity(EuroOptionData od, double S);
double EuroPutParity(EuroOptionData od, double S);
//EuroOption class operators
EuroOption& operator = (const EuroOption& option2); //Assignment Operator
};
#endif
And a snippet of the EuroOption.CPP file:
//
//
//
#include "EuroOption.hpp"
#include <cmath>
#include <iostream>
using namespace GLOBAL;
{
double EuroOption::EuroCallPrice(EuroOptionData od, double S)
{
return CallPrice(od,S);
};
double EuroOption::EuroPutPrice(EuroOptionData od, double S)
{
return CallPrice(od,S);
};
.....
...
}
And finally, a snippet of my Test.CPP file where I test functionality:
//
//
//
#include "Global.hpp"
#include "EuroOption.hpp"
#include <iostream>
using namespace GLOBAL;
int main()
{
EuroOption Batch1; //Initialize EuroOption class object Batch1
cout << "S1: "; double S1; cin >> S1;
cout << "Stock Call Option: " << EuroCallPrice(Batch1.od, S1) << endl;
cout << "Stock Put Option: " << EuroPutPrice(Batch1.od, S1) <<endl;
cout << "Put Call Parity - Call Option:"<< EuroCallParity(Batch1.od, S1)<<endl;
cout << "Put Call Parity - Put Option: "<< EuroPutParity(Batch1.od, S1)<<endl;
//****None of these functions compile. They all state "identifier EuroCallPrice (..etc.) is undefined."
cout << "S1: "; double S1; cin >> S1;
cout << "Stock Call Option: " << CallPrice(Batch1.od, S1) << endl;
cout << "Stock Put Option: " << PutPrice(Batch1.od, S1) <<endl;
cout << "Put Call Parity - Call Option:"<< CallParity(Batch1.od, S1)<<endl;
cout << "Put Call Parity - Put Option: "<< PutParity(Batch1.od, S1)<<endl;
//****These functions all compile properly. They are the original global functions.
I realize this is a lot of code to sift through, but any ideas would be greatly appreciated. As noted in the above code, the original global functions work perfectly, but I want to use the class EuroOption function to call that global function.
Many thanks!
Silly me! All i needed to do was call the EuroCallPrice...etc functions on Batch1.
Thanks for all your help!

C++ : unresolved overloaded function when using function pointers

#include <iostream>
using namespace std;
class B
{
public:
int getMsg(int i)
{
return i + 1;
}
};
class A
{
B b;
public:
void run()
{
taunt(b.getMsg);
}
void taunt(int (*msg)(int))
{
cout << (*msg)(1) << endl;
}
};
int main()
{
A a;
a.run();
}
The above code has a class B inside a class A, and class A has a method taunt that takes a function as an argument. class B's getMsg is passed into taunt...The above code generated the following error message: "error: no matching function for call to 'A::taunt()'"
What's causing the error message in the above code? Am I missing something?
Update:
#include <iostream>
using namespace std;
class B
{
public:
int getMsg(int i)
{
return i + 1;
}
};
class A
{
B b;
public:
void run()
{
taunt(b.getMsg);
}
void taunt(int (B::*msg)(int))
{
cout << (*msg)(1) << endl;
}
};
int main()
{
A a;
a.run();
}
t.cpp: In member function 'void A::run()':
Line 19: error: no matching function for call to 'A::taunt()'
compilation terminated due to -Wfatal-errors.
I'm still getting the same error after changing (*msg)(int) to (B::*msg)(int)
b.getMsg is not the correct way to form a pointer to member, you need &B::getMsg.
(*msg)(1) is not the correct way to call a function through a pointer to member you need to specify an object to call the function on, e.g. (using a temporary) (B().*msg)(1).
The right way to do such things in OOP is to use interfaces so all you need to do is to define an interface and implement it in B class after that pass the pointer of instance which implements this interface to your method in class A.
class IB{
public:
virtual void doSomething()=0;
};
class B: public IB{
public:
virtual void doSomething(){...}
};
class A{
public:
void doSomethingWithB(IB* b){b->doSomething();}
};
This works in VS 2010. The output is the same on all lines:
#include <iostream>
#include <memory>
#include <functional>
using namespace std;
using namespace std::placeholders;
class A
{
public:
int foo(int a, float b)
{
return int(a*b);
}
};
int main(int argc, char* argv[])
{
A temp;
int x = 5;
float y = 3.5;
auto a = std::mem_fn(&A::foo);
cout << a(&temp, x, y) << endl;
auto b = std::bind(a, &temp, x, y);
cout << b() << endl;
auto c = std::bind(std::mem_fn(&A::foo), &temp, _1, y);
cout << c(5) << endl;
}
Basically, you use std::mem_fn to get your callable object for the member function, and then std::bind if you want to bind additional parameters, including the object pointer itself. I'm pretty sure there's a way to use std::ref to encapsulate a reference to the object too if you'd prefer that. I also included the _1 forwarding marker just for another way to specify some parameters in the bind, but not others. You could even specify everything BUT the class instance if you wanted the same parameters to everything but have it work on different objects. Up to you.
If you'd rather use boost::bind it recognizes member functions and you can just put it all on one line a bit to be a bit shorter: auto e = boost::bind(&A::foo, &temp, x, y) but obviously it's not much more to use completely std C++11 calls either.