Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a member using its parameterized constructor

It's hard to describe without code so here goes: I'm trying to prototype an object (b) in the header file of another(a), then in the constructor of (a) call (b)'s constructor and pass it values, so i can then use the methods of b which depend on its constructor and the values passed to it, but the way im doing gives: red underlined in the open bracket of pricing's constructor says: "no default constructor exists for monteCarlo" and then on the next line m is underlined red saying: "call of object of a class type without appropriate operator() or conversion functionsto pointer-to-function type". Any other critic of my program is very welcome, i am trying to learn to program, and well.

in the file pricing.cpp i have:

#include "pricing.h"
#include <math.h>
#include <vector>
pricing::pricing(void)
{
 m(10,0.0,0.01,50);
}
double pricing::expectedValue(void)
{
expectedExValue = m.samplePaths[2][3]; //yes this isn't an expected value, 
// its just for illustration purposes/making it compile.
return 0;
}

in pricing.h i have:

#pragma once
#include "pricing.h"
#include "monteCarlo.h"
class pricing
{
public:
pricing(void);
~pricing(void);
double euroCall();
std::vector<double> samplePathing;
double expectedValue();
    monteCarlo m;

};

then montecarlo.cpp looks like:

#include "monteCarlo.h"
#include "randomWalk.h"
#include <vector>
#include <iostream>

monteCarlo::monteCarlo(int trails, double drift, double volidatity, int density)
{
for (int i = 0; i < trails; i++)
{
    std::cout << "Trail number " << i+1 <<  std::endl;
    randomWalk r(drift,volidatity,density);
    r.seed();
    samplePaths.emplace_back(r.samplePath);
    std::cout << std::endl << std::endl;
}
}


monteCarlo::~monteCarlo(void)
{
}

and finally montecarlo.h is:

#pragma once
#include <vector>

class monteCarlo
{
public:
monteCarlo(int, double, double, int);
~monteCarlo(void);
std::vector< std::vector<double> > samplePaths;
};
like image 220
Rob Spencer Avatar asked Jan 20 '26 09:01

Rob Spencer


1 Answers

pricing::pricing(void)
{
 m(10,0.0,0.01,50);
}

This attempts to call m as though it were a function (if it had overloaded operator(), you would be able to do this, which is what the error is talking about). To initialise m instead, use the member initialization list:

pricing::pricing(void)
 : m(10,0.0,0.01,50)
{ }

This colon syntax is used to initialise members of an object in the constructor. You simply list members by their names and initialize them with either ( expression-list ) or { initializer-list } syntax.

like image 189
Joseph Mansfield Avatar answered Jan 21 '26 22:01

Joseph Mansfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!