I have got the following code and I got an unexpected result does anybody know why that happened??!!
#include <iostream>
using namespace std;
class A2
{
public:
void disp ()
{
cout<<m<<endl;
}
private:
int m = 4;//this is the data member I want to show
};
int main()
{
A2 al;
al.disp();// the output of this is 4
A2 *a2;
a2->disp();
//here is the unexpected result, I think that it should be 4
return 0;
}
CodePudding user response:
a2
here is just uninitialized. You must make a2
point to the object and then call the function.
A2* a2 = &al; // points to a1
a2->disp();
Or
A2* a2 = new A2(); // constructs another A2 objcet and points to
a2->disp();
delete a2;
More about pointers, see https://en.cppreference.com/w/cpp/language/pointer
CodePudding user response:
In your line:
A2 *a2;
You have to complete with:
A2 *a2 = new A2();