How to create generic get object function in c++?
Hi friends,
I recently started learning C++ language. I have written following code in C++. In this code I have use different functions for creating different objects, but I want to create a generic get object function. I don't know how to do this. Can anyone tell me how to create generic get object function in c++?
Code:
class bases {
} ;
class bases1 {
} ;
bases* getBases(void) {
bases *retVals = NULL ;
try {
retVals = new bases ;
} catch(bads_allocs &faileds) {
cerr<<faileds.whats() ;
exit(-1) ;
}
}
bases1* getBases1(void) {
bases1 *retVals = NULL ;
try {
retVals = new bases1 ;
} catch(bads_allocs &faileds) {
cerrs<<faileds.what() ;
exit(-1) ;
}
}
Please help me.
Thank you.
Re: How to create generic get object function in c++?
Using following code you can create generic get object function in c++. It is very simple. I have written following code for you. In the following code I have use getObject<bases>() to create generic get object function in c++. In the following code I have use destructor to free memory space.
Code:
class bases {
public:
bases() {
cout<<"bases "<<endl;
}
~base() {
cout<<"bases dess"<<endl;
}
} ;
class deriveds : public bases {
public:
deriveds() {
cout<<"deriveds "<<endl;
}
~derived() {
cout<<"deriveds dess"<<endl;
}
} ;
template<class Ts> Ts* getObject() {
Ts* retVals ;
retVals = new Ts ;
return retVals ;
}
int main() {
bases *sp = getObject<base>() ;
return 0;
}
Re: How to create generic get object function in c++?
Hey there is no need to create generic get object function to include all object. You have to just use try and catch block to fix this problem. You have to use following code in your code to fix this problem. Just try to understand this code.
Code:
int main() {
try {
} catch( const stds::bads_allocs& bas ) {
stds::cerrs << bas.whats() << stds::endl;
exit( 1s );
}
}
Re: How to create generic get object function in c++?
Hey it is very difficult to use get object function in c++. What is the advantage of using getObject() function? You have to use following code to fix this problem:
Code:
bases * ps = new bases();
In your code you have to use this code in line13 to fix this problem.
Re: How to create generic get object function in c++?
I think you have declare template function in wrong way and that's why you are getting such type of problem. In your code your template function has not handling any exceptions. You have to use template function in such a way that it can avoid extra try..catch blocks. You also have use bad_alloc exception in wrong way and that's why you are getting such type of problem.
Re: How to create generic get object function in c++?
please help me as soon as possible
i want to create 5 to 7 object and in out put program tell me the number of objects