I am defining a class outside a function and inside a function and returning the address of the object using new to main. I have no problems when the class definition is outside any objects but when I initialize the class definition within a function I am getting errors, this happens even when I use a forward declaration. How should I fix this?? Below is the code when I declare the class outside function:

#include<iostream>

class XYZ{

private: 
int m;

public:

void setm(int x){


m=x;

}

void showm(void){

std::cout<<"M = "<<m<<std::endl;
}
};

XYZ * dynmem(void);

int main()
{


XYZ *xyz = dynmem();

xyz->setm(55);
xyz->showm();

delete xyz;







return 0;
}



XYZ * dynmem(void){
/*
class XYZ{

private: 
int m;

public:

void setm(int x){


m=x;

}

void showm(void){

std::cout<<"M = "<<m<<std::endl;
}
};
*/
XYZ *xyz = new XYZ();

return xyz;

}

Below is the code when I declare a class in a function:

#include<iostream>

class XYZ;

XYZ * dynmem(void);

int main()
{


XYZ *xyz = dynmem();

xyz->setm(55);
xyz->showm();

delete xyz;







return 0;
}



XYZ * dynmem(void){

class XYZ{

private: 
int m;

public:

void setm(int x){


m=x;

}

void showm(void){

std::cout<<"M = "<<m<<std::endl;
}
};

XYZ *xyz = new XYZ();

return xyz;

}

Standard C and C++ do not support nested functions, but:
GCC supports nested functions in C, as a language extension...

https://en.m.wikipedia.org/wiki/Nested_function

Note: in C++, it seems you are limited in 'nesting classes' to ... you can 'nest' a class inside a class.

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.