rahul valluri
rahul valluri

Reputation: 15

Derived class nested inside base class - C++

I am trying to transform the following JAVA code to C++ code. But unable to figure out how.

abstract class Base {
   static class Derived extends Base {
      // attributes

      Derived(/*params list*/) {
        // code
      }


}

When I try to do something like below, the compiler says Base is not complete until the closing brace. I understand that things don't work the same way as JAVA, but I am unable to figure out how to reproduce this code in C++.

class Base {
        class Derived: public Base{
        // attributes
        Derived(/* param list*/);
    };
 };

Is it possible to do this in C++? Open to non-object-oriented approaches too.

Upvotes: 0

Views: 60

Answers (1)

fabian
fabian

Reputation: 82531

This can be done. Just add a forward declaration to the body of Base and move the definition below the definition of Base:

class Base
{
    class Derived;
public:
    virtual ~Base() = default;
protected:
    Base() = default; // only allow initialization for subclasses to make this "abstract" without introducing a pure virtual function
};

class Base::Derived : public Base
{
    // attributes

    Derived(/*params list*/) {
        // code
    }
};

Upvotes: 1

Related Questions