Search code examples
c++inheritancevirtual

problem with inheritance


class OGraph {
public:
    OGraph() { }
    virtual ~OGraph();

    virtual bool is_directed()=0;
};

class OUGraph : public OGraph {
public:
    OUGraph() {  }
    bool is_directed() { return false; }
    ~OUGraph() {}
};

but when I do this

OUGraph myGraph();
cout << myGraph.is_directed();

I get the following error:

Undefined symbols: "typeinfo for OGraph", referenced from: typeinfo for OUGraphin main.o "vtable for OGraph", referenced from: OGraph::OGraph()in main.o mkdir -p dist/Debug/GNU-MacOSX "OGraph::~OGraph()", referenced from: g++ -o dist/Debug/GNU-MacOSX/opengraph build/Debug/GNU-MacOSX/OGraph.o build/Debug/GNU-MacOSX/main.o
OUGraph::~OUGraph()in main.o OUGraph::~OUGraph()in main.o ld: symbol(s) not found collect2: ld returned 1 exit status make[2]: * [dist/Debug/GNU-MacOSX/opengraph] Error 1 make[1]: [.build-conf] Error 2 make: ** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 568ms)


Solution

  • You have no implementation provided for virtual ~OGraph();. Either provide an implementation, specify it as pure virtual with = 0;, or just get rid of it.

    The compiler is expecting to attach type info for the class to the implementation of its first virtual method. Your first virtual method is undefined, so the implementation is never generated, and you get related linking errors.

    Additionally, as everyone is saying, you should remove the parentheses from your definition of myGraph.