operators in derived classes??

Discussion in 'C++' started by Niels Lauritzen, Aug 6, 2003.

  1. 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
    Niels Lauritzen, Aug 6, 2003
    #1
    1. Advertising

  2. Niels Lauritzen

    tom_usenet Guest

    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
    tom_usenet, Aug 6, 2003
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Colin Goudie
    Replies:
    6
    Views:
    466
    Victor Bazarov
    Jan 26, 2004
  2. Manuel
    Replies:
    8
    Views:
    634
    Manuel
    Jan 5, 2006
  3. Replies:
    6
    Views:
    365
  4. Replies:
    1
    Views:
    393
    myork
    May 23, 2007
  5. Replies:
    1
    Views:
    385
    Victor Bazarov
    May 23, 2007
Loading...

Share This Page