0

I understand that it is bad practice to inherit from a STL container, but my assignments requires that I use inheritence instead of composition. I have to "inherit from std::vector and you need to choose whether public or private inheritance is the best choice." I am to support the following operations with the given signatures. I am using private inheritence, but I am having trouble with my .cpp file on how I use the vector STL container to implement these functions. I am used to using composition.

#ifndef STACK_H
#define STACK_H

#include <vector>
#include <stdexcept>

// Use inheritance from std::vector (choose public/private) as appropriate
template <typename T>
class Stack : private std::vector<T>
{
public:
    Stack();
    ~Stack();
    bool empty() const;
    size_t size() const;
    void push(const T& item);
    void pop();  // throws std::underflow_error if empty
    const T& top() const; // throws std::underflow_error if empty
    // Add other members only if necessary
};
Lucia
  • 1

1 Answers1

0

It all depends on whether you only want the methods you define in the Stack class as the interface of the class, if so you would have to inherit private, since, when you inherit public, all the elements of the Super class pass to the interface of the Subclass.

From the post of private inheritance:

From a common understanding of inheritance, C++’ “private inheritance” is a horrible misnomer: it is not inheritance (as far as everything outside of the class is concerned) but a complete implementation detail of the class.

Seen from the outside, private inheritance is actually pretty much the same as composition. Only on the inside of the class do you get special syntax that is more reminiscent of inheritance than composition.

About .cpp file problems i can't help you without watching the code.

Hope it helps.

TPerez
  • 1
  • 1