|
-
June 2nd, 2013, 09:12 AM
#1
operator overloading and inheritance
Hi,
So i am having troubles with operator overloading in inherited class. Basically, it doesnt work. Consider this:
Code:
class A
{
public:
A()
{
x=0;
z= new int;
}
~A()
{
delete z;
}
int x;
int* z;
A& operator=(A& a)
{
x = a.x;
z = new int(*a.z);
return *this;
}
};
class B : public A
{
public:
B(){y=0;}
B(B& b, int dummy) //pseudo-assignment constructor
{
operator=(b);
}
int y;
B& operator=(B& b)
{
y = b.y;
A::operator=(b);
return *this;
}
};
void somefunc(B& b)
{
/*
some how the copy constructor of a is improperly executed - the pointer is copied over, not re-created.
As a result, the destructors crashes due to double-free.
*/
B bb = b; //doesnt work
B bbb(b); //doesnt work
B bbbb(b, 0); //works
}
Above code shows the problem well. The "official" copy-constructor wont work - it copies over the pointer directly, and doesnt create a new one as it should. However, if i provide my own pseudo-copy-constructor that works.
But ofcourse it's just a cheap work around - and wont actually work in real code (STL).
What's wrong? Strikes me as very odd...
compiler is VS2008SP1.
edit:
I have added a proper example, sorry.
Last edited by tuli; June 2nd, 2013 at 10:00 AM.
Reason: foramtting
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|