operators in derived classes??

  • Thread starter Niels Lauritzen
  • Start date
N

Niels Lauritzen

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 (e-mail address removed)
 
T

tom_usenet

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top