|
-
February 17th, 2003, 06:04 AM
#1
Initializing valarray and inheritence
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
-
February 17th, 2003, 07:11 AM
#2
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.
Code:
#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;
}
You're gonna go blind staring into that box all day.
-
February 17th, 2003, 08:01 AM
#3
Thanks that has sorted it out
-
February 17th, 2003, 10:19 AM
#4
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)
{
}
Last edited by mwilliamson; February 17th, 2003 at 10:22 AM.
-
February 17th, 2003, 10:34 AM
#5
The second solution is simpler.
Thanks. Chris.
You're gonna go blind staring into that box all day.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|