Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > operators in derived classes??

Reply
Thread Tools

operators in derived classes??

 
 
Niels Lauritzen
Guest
Posts: n/a
 
      08-06-2003
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


 
Reply With Quote
 
 
 
 
tom_usenet
Guest
Posts: n/a
 
      08-06-2003
On Wed, 6 Aug 2003 15:09:27 +0200, "Niels Lauritzen" <>
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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Derived Structure in Derived Class?? David C++ 3 01-29-2008 07:38 AM
Derived::Derived(const Base&) and Derived& operator=(const Base&) developereo@hotmail.com C++ 1 05-23-2007 01:44 PM
Derived::Derived(const Base&) developereo@hotmail.com C++ 4 05-23-2007 09:32 AM
Derived::Derived(const Base&) and Derived& operator=(const Base&) developereo@hotmail.com C++ 1 05-23-2007 12:07 AM
Math Operators MtnSurf8 VHDL 0 04-25-2004 07:08 AM



Advertisments