By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,804 Members | 1,666 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,804 IT Pros & Developers. It's quick & easy.

operators in derived classes??

P: n/a
CONSIDER:

#include <valarray>

class ivec : public valarray<int>
{
public:
ivec(size_t sz) : valarray<int>(sz){};
void t();
};

int main()
{
ivec w(1);
(-w).t();
}

The return type of -w above is valarray<int> and not the derived type ivec.
This results
in a COMPILATION ERROR.

Is there a neat way of reusing the unary -operator of valarray<int> above?
To make
a type conversion to ivec?
Regards,
Niels Lauritzen ni***@imf.au.dk
Jul 19 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On Wed, 6 Aug 2003 15:09:27 +0200, "Niels Lauritzen" <ni***@imf.au.dk>
wrote:
CONSIDER:

#include <valarray>

class ivec : public valarray<int>
{
public:
ivec(size_t sz) : valarray<int>(sz){};
void t();
};

int main()
{
ivec w(1);
(-w).t();
}

The return type of -w above is valarray<int> and not the derived type ivec.
This results
in a COMPILATION ERROR.

Is there a neat way of reusing the unary -operator of valarray<int> above?
To make
a type conversion to ivec?


The problem is that valarray is not intended to be used as a base
class (it doesn't have any virtual functions), but as a building block
to be used by other classes - IOW, use composition, not inheritence.
If you are just trying to add additional operations, use non-member
functions. e.g.

void t(valarray<int>& v);

However, you can't then do

t(-w); //error, can't bind temporary to non-const reference

since you pass by non-const ref (and this is no bad thing in this
example). Perhaps you actually wanted a const operation:

void t(valarray<int> const& v);

t(-w); //works fine now

Tom
Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.