Radde wrote:
Hi all,
[...] int main()
{
A a;
delete a; // Error
return 0;
}
In the above code, when i delete a( a object allocated on stack). What
error compiler supposed to give. First of all, is this allowed in C++.
If not, does all compiler gives error, if so what error??
ken@ken-wn0vf73qmks ~/c
$ cat classExample.cpp
#include <iostream>
class A {
public:
A();
A(int s);
~A();
private:
int * iArray;
int size;
};
A::A() {
std::cout << "No argument constructor." << std::endl;
iArray = new int[1];
}
A::A(int s)
:
size(s)
{
std::cout << "One argument constructor, s: " << s << '.'
<< std::endl;
iArray = new int[s];
}
A::~A() {
std::cout << "Destructor." << std::endl;
delete [] iArray;
}
int main(void) {
A a1; /*This is an object of type A*/
A *a2 = new A; /*This is a pointer to an object of type A*/
/*delete a1;*/ /*Here you're trying to delete an object, it
doesn't work. Let the destructor do its
job when a1 goes out of scope*/
delete a2; /*Here you're trying to delete what a2 points
to. This calls a2's destructor and then frees
the memory pointed to by a2.*/
return 0;
}
ken@ken-wn0vf73qmks ~/c
$ g++ -o classExample classExample.cpp
ken@ken-wn0vf73qmks ~/c
$ ./classExample.exe
No argument constructor.
No argument constructor.
Destructor.
Destructor.
The error you'd get if `delete a1;' wasn't commented out would be
something about delete expecting a pointer rather than an `A' or `class
A.' It's not allowed in C++ and every compiler should give a similar error.