Accessing protected member function in derived class — Segmentation fault

849 Views Asked by At

I am trying to use OGDF C++ library for a project and want to use a protected member function of a class of this library. I can't access protected members directly outside class or derived class, so to use protected method of Balloon Layout class I created a class A which inherits from BallonLayout. From A, a protected function of the super class is called in a public function abc() of class A; so that I can use abc() outside the class and indirectly protected function of class BallonLayout.

Here's the code, please tell me where there is a problem in it.

#include <ogdf/basic/Graph.h>
#include <ogdf/basic/graph_generators.h>
#include <ogdf/misclayout/BalloonLayout.h>

using namespace ogdf;

class OGDF_EXPORT A : public BalloonLayout{
        public:
            void abc(const Graph &G){
            selectRoot(G); //Calling super class protected method.               
            }
};

int main()
{
    int n = 5, m = 7;
    Graph G;
    ogdf::planarBiconnectedGraph(G, n, m);

    A* a = new A;
    a->abc(G);
    cout << "Done!!";
return 0;

}

It compiles without any error but at run time it gives “Segmentation fault (core dumped)”. This error comes when we try to access something (object/variable) which is not in memory. But I do not understand what mistake have I done.

In place of A* a = new A; a->abc(G);, I tried the following too but I am getting the same error.

A* a; 
a->abc(G);

and

A *a = new A;
a->abc(G);
delete a;

and

A a;
a.abc(G);

Foe each one of the attempts above, I get a segmentation fault. This error is coming after calling a.abc(G) when this method calls the superclass's method.

1

There are 1 best solutions below

7
Mike Seymour On
A* a;
a->abc(G);

That creates a pointer without initialising it; then attempts to dereference that invalid pointer to call a function. The result is a segmentation fault, or other undefined behaviour.

You almost certainly want to create an object:

A a;
a.abc(G);