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;
}