Patrick
Patrick

Reputation: 181

C++ abstract class with nested class

I want to design a base class with some nested structure:

class base {
public:
  struct PtrType;
  virtual bool free(const PtrType& ptr) = 0;
};

for forcing all the derived class to implement their own PtrType, like:

class derived : public base {
 public:
   struct PtrType {
     int a;
   };
   bool free(const PtrType& ptr) override { return true; }
};

But this implementation encounters two problems:

  1. the compiler allow the derived class nested PtrType's free unimplemented, if I write the base as
class base {
public:
 struct PtrType{
   virtual bool free() = 0;
 };
 virtual bool free(const PtrType& ptr) = 0;
};
  1. the override keyword is not allowed.

My question is, how should I implement this base class to force all the derived class to implement some certain nested classes?

Upvotes: 0

Views: 257

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117178

I'm not sure I understand why you want this, but to solve the override problem you need to make derived::PtrType inherit from base::PtrType since they are currently two unrelated classes.

Example:

class base {
public:
    struct PtrType{};
    virtual bool free(const PtrType& ptr) = 0;
};

class derived : public base {
public:
    struct PtrType : base::PtrType {
        int a;
    };
    bool free(const base::PtrType& ptr) override { return true; }
};

Note that the name of derived::PtrType doesn't matter here. You could make it:

class derived : public base {
public:
    struct Foo : base::PtrType {
        int a;
    };
    bool free(const base::PtrType& ptr) override { return true; }
};

Upvotes: 1

Related Questions