2

Is the following a valid design in C++?

#include <iostream>
#include <memory>

using namespace std;

struct Base {
    virtual void SomeMethod() {
        std::cout<<"Do Something"<<std::endl;
    }
};

struct Der : public Base {
    virtual void SomeMethod() override = 0;
};

struct DerDer : Der {
    virtual void SomeMethod() override
    {
        std::cout<<"Do something derived."<<std::endl;
    }
};

int main(int argc, char *argv[])
{
    auto x = std::unique_ptr<Base>(new DerDer);
    x->SomeMethod();
    return 0;
}

It works on g++ 6.2.

I'm deriving from a normal class, converting that method to abstract, and then overriding it after deriving again.

Is it correct in C++ to derive from a class, and then turn an implemented method back to abstract?

The reason I need to do this, is that in a big program, to which I'm adding features, I'm trying to avoid a diamond model. To do that, I'm planning to put all common methods in the class Der, and make everything inherit from it, without messing with the Base class.

Community
  • 1
  • 1
The Quantum Physicist
  • 24,987
  • 19
  • 103
  • 189

3 Answers3

0

That's legal.

But if you want avoid the diamon model, there are another workarounds

Community
  • 1
  • 1
amchacon
  • 1,891
  • 1
  • 18
  • 29
  • The answers to the linked question show how to create a diamond shaped hierarchy. Not how to avoid it. – eerorika Mar 27 '17 at 10:39
  • @user2079303 I was gonna say that. You beat me to it! – The Quantum Physicist Mar 27 '17 at 10:42
  • Uh, i think that right sentence is: "avoid the problems of the diamon model" :) – amchacon Mar 27 '17 at 10:43
  • @amchacon not quite technically correct either. The *problem* that the OP of the linked question has is that there are two base classes of same type, which results in ambiguity. The *solution* to that problem is to create a "diamond model". The diamond model also has problems sure, but those are not avoided by virtual inheritance. Virtual inheritance is what creates the "diamond model". – eerorika Mar 27 '17 at 10:54
0

absolutely legal. Consider it as just implementation of pure virtual function if you like. See discussion here pure virtual function with implementation

Community
  • 1
  • 1
Peregrin
  • 424
  • 4
  • 11
-1

Technically there would not be any problem but it is never a good design when you inherit interface (or abstract class) from a concrete class.

If you are going to provide some common functionality in Der, you can use composition. Because your class Der would be like a utility class. Don't make der class as abstract class.

Class DerDer : class base
{
  private der ptrUtilityObj;
}

In future, might be some new developer will confuse that he should introduce new functionality in Base class or Der class.