pepero
pepero

Reputation: 7513

how to customize the nested class's methods in C++

I have a class A with nested class Inner_vector,

class A: 
{
public: 
  class Inner_vector:public Vector
    {
      bool append(const class Element& element);
    };
};
bool A::Inner_vector::append(const class Element& element)
{
   add(element);
}

Now I want to derive a child class from A and also customize the "append" and "delete" methods of the inner class "Inner_vector" (mainly to add one new operation), so that the customized operations will be called instead. How could I do it? should I also derive a new nested class inside Child_A from A::Inner_vector as the following code

class Child_A: public A
{
public: 
  class Inner_Child_vector : public A::Inner_vector
    {
      bool append(const class Element& element);
    };
};
bool Child_A::Inner_Child_vector::append(const class Element& element)
{
   A::Inner_vector::append();
   my_new_operation();
}

Or I do not need to derive from A::Inner_vector and directly rewrite it?

I really appreciate any help and comments.

Upvotes: 4

Views: 667

Answers (2)

Sergio Franco
Sergio Franco

Reputation: 98

You could always not create another class for inner_vector and have it a protected member in your outer class 'A', class 'A' can then define two virtual functions append and delete.

Which means when you inherit and create 'Child_A' you just define a new behaviour for append and delete. This will require you to extend your inner vector class to give you enough access to its internals that you can create the append and delete behaviours you want from the classes that contain it.

class A 
{
 public: 
  virtual bool append( const class Element& element )
  {
    //  your specific A behaviour
  }     

 protected:
  // std::vector or your own implementation
  std::vector _innerVector;

};

class Derived : public A
{
 public:
  virtual bool append( const class Element& element )
  {
    // derived implementation
  }
};

If this is not possible then you have to derive both classes as they are unrelated.

Upvotes: 1

Jan Hudec
Jan Hudec

Reputation: 76316

In C++, inner classes are unrelated to the classes containing them except for scoping. So you have to derive the base's inner class in the derived class.

Upvotes: 6

Related Questions