0

Hi I have a derived class and I want to pass the pointer of the derived class object to the base class. I am getting segmentation fault while running the code.

#include <iostream>
using namespace std;

class A {
    public:
    virtual void x() = 0;
    A* a;
};

class B: public A {
public:

  B(A* x) {
    a = x;
  }

 void x () {}

};

class C: public B {
    public:
    C() : B(new C) { } 
};

int main() {
    C c;
    return 0;
}

Can someone help me suggest a way to achieve this or help me in fixing the code.

1 Answers1

0

I believe you want to pass a pointer to current object. This is what this is for.

C() : B(this) { } 
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • I am a bit new to C++. Don't I need to allocate space to the class pointer ? – user2033594 May 22 '20 at 06:17
  • @user2033594 No you don't. `this` just points to the object `C` that you've created. But I don't see the benefit of storing it in the base class, as you simply can use `this` in the base class. – StefanKssmr May 22 '20 at 06:32