pointers - Call base class constructor after the derived class constructor in C++ -
consider following situation:
#include <iostream> using namespace std; class { public: int y; a(int &x) { x = 2; y = 1; } }; class b : public { public: int *p; b(int t) : a(*p) {} }; int main() { b b(2); return 0; }
when constructor of b called, p
has junk value. so, when *p
passed a()
, gives me segmentation fault. want initialize p = new int;
before calling a(*p)
- possible?
edit: interestingly, calling b
's constructor without arguments didn't give segmentation fault.
the way introduce other struct:
class { public: int y; a(int &x) { x = 2; y = 1; } }; struct c { explicit c(int* p) p(p) {} int* p; } class b : private c, public { public: b(int t) : c(new int), a(*p) {} ~b() {delete p;} b(const b&) = delete; b& operator =(const b&) = delete; };
Comments
Post a Comment