After searching through this forum and other forums relating to C++ and Dynamic Memory; I would like to know the indepth reason on why do you have to declare a dynamic memory allocation in either a Class or in a function for the program to compile?

e.g.

//place a dynamic memory allocation here and the program won't compile

int main (void)
{

int * Total_N;
Total_N = new int; //place a dynamic memory allocation here and the program compiles

}

As the book I'm learning from doesn't go into an indepth explanation, so any help would be appreciated. Thank you.

The error you are asking about is not just for dynamic memory it is for any time you try to assign outside of a function.

You can declare outside of functions like int *sean = new int; but sean = new int; will give you an error because you are not declaring assigning the variable and declaring at the same time.

.

This is what he was trying to do and it was giving him an error.

#include <iostream>

using namespace std;

int *sean; //declaring variable
sean = new int; //cant assign out of a function without declaring at the same time

int main()
{
	//int *sean = new int;
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.