Pointer error when debugging.

My code is compiling but i receive error when i run with the debugger

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 Aplicatie::Aplicatie()
	{
		UI::MeniuPrincipal *_pMeniu = new UI::MeniuPrincipal; 
	};

	Aplicatie::~Aplicatie()
	{
		delete _pMeniu; 
	};

	void Aplicatie::Run()
	{
		do
		{
			_pMeniu->Execute(); //The error shows here Unhandled exception at 0x0130254d in Calculator.exe: 0xC0000005: Access violation reading location 0xcccccccc.
		} while (!_pMeniu->Exit());
        };	

I can't understand this message, maybe the error is in another class.
surround it with a try catch and print the stack trace or exact exception.
in your constructor you do not initialize the member variable, just a local variable.
_pMeniu in Run() is still uninitialized

1
2
3
4
 Aplicatie::Aplicatie()
	{
		UI::MeniuPrincipal *_pMeniu = new UI::MeniuPrincipal; // local variable!
	};
1
2
3
4
5
6
class Aplicatie{
   UI::MeniuPrincipal Meniu;
public:
   Aplicatie() = default;
   ~Aplicatie() = default;
};
Ok i got it :)

void Aplicatie::Run()
{
UI::MeniuPrincipal *_pMeniu = new UI::MeniuPrincipal;
do
{
_pMeniu->Execute();
} while (!_pMeniu->Exit());
};

Now it works correct. Thanks
if you're creating a variable that all the functions of your object uses, then maybe that variable should be a member of the class.
why don't you try this:

1
2
3
4
5
6
7
8
9
10
11
class Aplicatie{
    UI::MeniuPrincipal *_pMeniu;
public:
    Aplicatie() { this->_pMeniu = new UI::MeniuPrincipal; }
    ~Aplicatie() { delete this->_pMeniu; }
    void Run();
};
void Aplicatie::Run()
{
    this->_pMeniu->Execute();
}


the solution that ne555 proposed is also convenient.

both are better than allocating an object in the constructor and leaking it, then creating another in the Run() method.
Topic archived. No new replies allowed.