Click to See Complete Forum and Search --> : Initializing valarray and inheritence


danielsbrewer
February 17th, 2003, 05:04 AM
Hi there I am pretty new to C++ object-orientated stuff and I was wondering if you could help. I have a class called Equations with a protected variable declared as:

valarray<double> myParameters;

I want to initialise this to a certain size during the constructor of the inherited class Model1. In the constructor I have:

valarray <double> myParameters(13);
myParameters[1]=2;

In another function of the Model1 class I have:
cout << myParameters[1] << endl;

But when this function is run it does not print "2" but some random amount. I concluded that i must be initialising it wrong.
Any ideas how to inherite a valarray object and initialise it to a certain size in the inherited class.

Thanks

dude_1967
February 17th, 2003, 06:11 AM
I would take care of this using a pointer to valarray initialized in the base-class constructor. Take a look at this sample.

Sincerely,
Chris.



#include <iostream>
#include <valarray>
using namespace std;

class base
{
protected:

valarray<double>* pv;

public:

base(const double d, const size_t s)
{
pv = new valarray<double>(d, s);
}
virtual ~base()
{
delete pv;
}

};

class derived : public base
{
public:

derived(const double d, const size_t s) : base(d, s)
{
}
~derived()
{
}

const double& operator[](const int n)
{
return (*pv)[n];
}

};

int main(int argc, char* argv[])
{
derived d(13.0, 100);

cout << d[0] << endl;

return 1;
}

danielsbrewer
February 17th, 2003, 07:01 AM
Thanks that has sorted it out

mwilliamson
February 17th, 2003, 09:19 AM
You need to add the contructor for valarray to your class' constructor, a pointer is NOT needed.

class CBase
{
public:
CBase(unsigned int nParamSize);
protected:
valarray<double> myParameters;
};

CBase(unsigned int nParamSize) : myParameter(nParamSize)
{
}

class CDerived
{
public:
CDerived(unsigned int nParamSize);
CDerived();
};

CDerived(unsigned int nParamSize) : CBase(nParamSize)
{
}

CDerived() : CBase(13)
{
}

dude_1967
February 17th, 2003, 09:34 AM
The second solution is simpler.
Thanks. Chris.

:)