(C++) Crash while calling outer class method in constructor which should set inner class's member

StackOverflow https://stackoverflow.com/questions/19693144

  •  02-07-2022
  •  | 
  •  

Domanda

I have two files:

test.h

#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED
class A{
  private:
    class B;
    B *bp;
  public:
    A(int val);
    void setX(int value);
};
#endif // TEST_H_INCLUDED

test.cpp

#include "test.h"

class A::B{
  int x;
  B(A &a, int value){
    a.setX(value);
  }
  friend class A;
};

A::A(int val) : bp(new B(*this, val)){
}

void A::setX(int value){
  bp->x = value;
}

While trying to create an object whose type is A I get a crash

A a(5);

After some debugging I found that program crashes on this line:

bp->x = value;

My guess is that since I am calling setX() from a constructor, bp isn't pointing at the class B instance which is being created. But what is the way around this? I don't want to duplicate the code of setX() in B constructor (this is just an example, as you can guess, the real code is longer).

È stato utile?

Soluzione

There is not much you can do other then to separate the construction of the A::B from its initialization to avoid this chicken-and-egg-problem:

class A::B{
    int x;
    void init(A &a, int value){
        a.setX(value);
    }
    friend class A;
};

A::A(int val) : bp(new B){
    bp->init(*this, val);
}

Altri suggerimenti

While Daniel's code would work, I would suggest using a member function in B. Then, you're simply going one direction (inward) and not bouncing back and forth between two classes. I don't know; maybe it's a personal preference.

class A::B{
public:
  B(int value){
    setX(value);
  }
  void setX(int value){
    x = value;
  }
private:
  int x;
};

A::A(int val) : bp(new B(val)){
}

void A::setX(int value){
  bp->setX(value);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top