[help] const_cast

K

Kaspar Minosiants

Hi ,
there is a question about work of const_cast

The question is why the object is still reachable after a delete operation

class A {
int var;
public:
A():var(0){}
~A(){}
void setVar(int a){var=a;}
int getVar() const {return var;}
int getVar() {return var;}
};
int main() {

const A* a=new A();
A *b=const_cast<A*>(a);
delete a;
b->setVar(10);
cout<<b->getVar();
return 0;
}
 
P

Peter van Merkerk

there is a question about work of const_cast
The question is why the object is still reachable after a delete operation

class A {
int var;
public:
A():var(0){}
~A(){}
void setVar(int a){var=a;}
int getVar() const {return var;}
int getVar() {return var;}
};
int main() {

const A* a=new A();
A *b=const_cast<A*>(a);
delete a;
b->setVar(10);
cout<<b->getVar();
return 0;
}

Undefined behaviour, anything might happen. const_cast has nothing to do
with this.
 
J

John Harrison

Kaspar Minosiants said:
Hi ,
there is a question about work of const_cast

The question is why the object is still reachable after a delete operation

class A {
int var;
public:
A():var(0){}
~A(){}
void setVar(int a){var=a;}
int getVar() const {return var;}
int getVar() {return var;}
};
int main() {

const A* a=new A();
A *b=const_cast<A*>(a);
delete a;
b->setVar(10);
cout<<b->getVar();
return 0;
}

Well what would you expect to happen? Its not a compile error, so what sort
of error?

The truth is that accessing an object after it has been deleted is an
example of 'undefined behaviour', which means ANYTHING could happen,
including your program 'working'.

This has nothing to do with const_cast.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top