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 AI 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).
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);
}
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.