0

I'm trying to implement a pure method from a class Algorithm to a class BasicAlgo like this :

class Algorithm
{
    public:
        virtual void solve() = 0;
};

class BasicAlgo : public Algorithm
{
    public:
         void solve() { };
};

Algorithm a = BasicAlgo();
a.solve();

But I'm getting this error :

variable type 'Algorithm' is an abstract class
    Algorithm a = BasicAlgo();
              ^
unimplemented pure virtual method 'solve' in 'Algorithm'
            virtual void solve() = 0;

After lots of time on Stackoverflow looking for a solution, I still don't really understand why there is an error. To me a.solve() is BasicAlgo::solve witch is well implemented.

Guillaume Wuip
  • 343
  • 5
  • 13

2 Answers2

4

C++ isn't Java.

Algorithm a = BasicAlgo();

The above attempts to define an object of type Algorithm by copy initializing it from a BasicAlgo. Even if it was to work (which it won't in this case, due to the pure virtual function that prohibits instantiating Algorithm objects), you would just slice your BasicAlgo object into an Algorithm.

For your purposes, you need a pointer or reference, like this:

std::unique_ptr<Algorithm> a = std::make_unique<BasicAlgo>();
a->solve();
Community
  • 1
  • 1
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • @GuillaumeWuip, You're welcome. I recommend you try to put your Java knowledge aside and approach c++ as a novice programmer would. They share some keywords, and are both "curly braces" languages, but that's where the similarity ends. They deal in completely different idioms. – StoryTeller - Unslander Monica Dec 04 '16 at 06:57
  • That's what my teacher is telling too. It's hard sometimes. C++ has a lot of this kind of extremely powerful features – Guillaume Wuip Dec 04 '16 at 07:00
  • @GuillaumeWuip, it does indeed. But it can be counter intuitive when we attempt and apply expectations from Java. (I'm not trying to beat on Java, it's just a different beast). [This post](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) has some of the best book recommendations, which I feel are a necessity for those learning c++. – StoryTeller - Unslander Monica Dec 04 '16 at 07:03
  • Thanks for your help and for this link @StoryTeller – Guillaume Wuip Dec 04 '16 at 09:25
1

Algorithm a = BasicAlgo(); doesn't allow for polymorphic behaviour - in fact, if the class wasn't abstract, you'd encounter slicing.

You can use std::unique_ptr to allow for inheritance polymorphism:

std::unique_ptr<Algorithm> a = std::make_unique<BasicAlgo>();
Community
  • 1
  • 1
milleniumbug
  • 15,379
  • 3
  • 47
  • 71