CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Threaded View

  1. #1
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    pimpl class with pointer to base class

    I'm trying to implement a class hierarchy and a wrapper class with a pointer to the base class. The base class has operator< overloaded and the implementation makes use of virtual functions as some of the logic for sorting is in the derived classes. Unfortunately, when trying to use the base class operator< from the wrapper, I get a "pure virtual method called".

    Below code is meant to illustrate my problem. Unfortunately it crashes on me (upon destruction of vec) and I cannot quite see, why. So two questions:

    1. Can somebody spot the error I made in the code below (having lived in Java-land for the last 5 years, I'm sure I just did some stupid error)?
    2. How can I implement Wrapper::operator< to use Base::operator<? I know I could write a function and pass it to sort but I'm interessted if there is a way to actually use Base::operator<.

    Code:
    #include <vector>
    #include <algorithm>
    #include <cmath>
    
    class Base {
    public:
      virtual ~Base() {}
      virtual int getValue() const = 0;
      virtual Base * clone() const = 0;
      bool operator<(const Base& rhs) const {
        return getValue() < rhs.getValue();
      }
    };
    
    class Derived : public Base {
    private:
      int value_;
    public:
      Derived() : value_(rand()) {}
      Derived(const Derived& rhs) : value_(rhs.value_) {}
      virtual Derived * clone() const { return new Derived(*this); }
      virtual int getValue() const { return value_; };
    };
    
    class Wrapper
    {
    private:
      Base * pimpl_;
    public:
      Wrapper() : pimpl_(new Derived()) {}
      Wrapper(const Wrapper& rhs) : pimpl_(rhs.pimpl_->clone()) {}
      ~Wrapper() { delete pimpl_; }
      bool operator<(const Wrapper& rhs) const {
        return pimpl_->getValue() < rhs.pimpl_->getValue();
      }
    };
    
    
    using namespace std;
    
    int main() {
      vector<Wrapper> vec(10);
      sort(vec.begin(), vec.end());
    }
    Thanks everybody.

    PS: Anybody else hates the new design?
    Last edited by treuss; June 28th, 2012 at 05:00 PM. Reason: Disabled smilieys
    More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf

    Premature optimization is the root of all evil --Donald E. Knuth


    Please read Information on posting before posting, especially the info on using [code] tags.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured