Reputation: 497
i'm writing a memory allocation program in c++ but got an error in the program.
i can't understand what is happening.
Please help.
#include<iostream>
using namespace std;
class Test{
int *m_ptr;
private:
void Test(){
m_ptr = new int(4);
}
~Test(class Test){
cout<<"Object gets destroyed..";
}
};
int main(){
Test *ptr = new Test();
delete [] ptr;
}
also i'm new to c++
Upvotes: 1
Views: 93
Reputation: 88092
private:
void Test(){
m_ptr = new int(4);
}
should be
public:
Test(){
m_ptr = new int(4);
}
There's no return type on a constructor, and if you want to use it in main
it should be public.
And
~Test(class Test){
cout<<"Object gets destroyed..";
}
should be
~Test(){
cout<<"Object gets destroyed..";
}
There are no parameters for a destructor and they should (almost always) be public.
Also
delete [] ptr;
should be
delete ptr;
If you allocate with new
then you deallocate with delete
. Only if you allocate with new[]
do you deallocate with delete[]
.
There's a lot of basic syntax errors in a very small program. Whatever source you are looking at to learn the structure of a C++ program cannot be very good. It might be worth spending some time practicing simpler topics before doing memory allocation (which is a very complex subject),
Thanks to dvix and user for helping me spot additional problems in the code.
Upvotes: 5
Reputation:
Your constructors and destructors (that are called) should be public
not private
.
Also, destructors don't take any arguments. It should be
~Test() {
cout<<"Object gets destroyed..";
}
Upvotes: 2