0

I need to change the pointer of a object inside a class. In this example I would like the call from the member function of b b->getBase(); in the main prints the value 2, and not 1.

int main(int argc, char *argv[])
{
base *b = new base(1);
top *t = new top( b);
b->getBase();
return 0;
}

base.h

class base
{
public:
    base(int _x);
    void getBase();
private :
    int x;
};

base.cpp

base::base(int _x):x(_x)
{
cout <<"base constructor:"<<x<<":";
};

void base::getBase()
{
cout <<"getBase()"<< x<< endl;
}

top.h

class top
{
public:
    top(base *b);
private:
    int topVar;
    base * b;
};

top.cpp

top::top(base * _b):b(_b)
{
    b->getBase();
    b = new base(2);
    b->getBase();
}

Results: base constructor:1 getBase():1 base constructor:2 getBase():2 getBase():1

RobertAalto
  • 1,235
  • 1
  • 9
  • 12
  • Pass a _reference_ to a pointer: `top::top(base*& b)`, so that the pointer in `main` changes too? Although a very strange thing to do... – Petr Oct 06 '15 at 10:16
  • Marked as dupe since that other question and it's accepted answer combined provide an answer to this one. – SingerOfTheFall Oct 06 '15 at 10:19
  • And some other things to change, mainly you need to change `_b`, not `b` in `top::top()`. – Petr Oct 06 '15 at 10:20
  • It works if I use : top::top(base *& b):b(b) but it does not work if I use: top::top(base *& _b):b(_b) why does is happen? – RobertAalto Oct 06 '15 at 11:22

0 Answers0