2

I'm a little confused how we have a vector which appears to holds pointers to objects of Statement datatype. But Statement is a pure virtual function, and as I understand it we cannot instantiate objects from a pure virtual class. What am I missing?

From the header file of Statements.hpp: (both Statement and Statements show up in this header file)

class Statement {
public:
    Statement();

    virtual void print() = 0;
    virtual void evaluate(SymTab &symTab) = 0;

};

class Statements {
public:
    Statements();

    void addStatement(Statement *statement);
    void evaluate(SymTab &symTab);

    void print();

private:
    std::vector<Statement *> _statements;
};

From the statements.cpp file:

void Statements::addStatement(Statement *statement) { _statements.push_back(statement); }

I'm a little confused. Let me know if I didn't supply enough code, I think this is everything that's pertinent. It's part of a interpeter.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
  • There must be, in your project or in a library you are using, one (or more) "non-virtual" class that extends `Statements` and that implements the virtual methods. – Leonardo Alves Machado Apr 04 '19 at 13:16
  • If a class is publicly derived from `Statement` and overrides all the inherited pure virtual functions, that class can be instantiated. And a `Statement *` can point at a valid instance of that derived class. Look up polymorphism for more information. – Peter Apr 04 '19 at 13:17
  • There is no contradiction here. Statement is an abstract class (it's not a function as you implied). You can't create objects of the Statement class, but you CAN create ones of derived types that implement all pure virtual functions. You can refer to those derived objects with pointers to the base class (Statement). That is the basis of polymorphism. – PlinyTheElder Apr 04 '19 at 13:18

1 Answers1

9

Statement is an abstract class, which means it has pure virtual functions. You are correct, being abstract means that instances of that class cannot be instantiated directly. However, other classes can derive from an abstract class, and those classes might implement all of the pure virtual functions, and therefore be concrete.

Because a subclass in this class hierarchy is an example of an object of the base class (it's an IS-A relationship), code can refer to it using a pointer or reference to the base class.

Classic example: if you have an Animal class, you can have subclasses called Dog and Cat. You can create instances of Dog and put them in a collection of Animal.

(This is pretty fundamental object-oriented theory stuff. Any book or article would cover it in better depth. Search for "polymorphism" "object oriented programming" "derived class" "concrete subclass" or any of a million other combinations.)

jwismar
  • 12,164
  • 3
  • 32
  • 44