|
Archives
D Programming
DD.gnu digitalmars.D digitalmars.D.bugs digitalmars.D.dtl digitalmars.D.ide digitalmars.D.dwt digitalmars.D.announce digitalmars.D.learn digitalmars.D.debugger C/C++ Programming
c++c++.announce c++.atl c++.beta c++.chat c++.command-line c++.dos c++.dos.16-bits c++.dos.32-bits c++.idde c++.mfc c++.rtl c++.stl c++.stl.hp c++.stl.port c++.stl.sgi c++.stlsoft c++.windows c++.windows.16-bits c++.windows.32-bits c++.wxwindows digitalmars.empire digitalmars.DMDScript electronics |
digitalmars.D.learn - Subclass->Base->Subclass help
Well I have some code that causes an access violation under DMD v2.012. I've
distilled it down to a mini-program that demonstrates the issue, but I don't
know if it's me doing something wrong or what.
Here's the code:
import std.stdio;
class SomeItem {
public:
bool some_var;
}
class BaseClass {
protected:
SomeItem alpha;
public:
this(SomeItem si) {
alpha = si;
si.some_var = true;
}
}
class NewItem : SomeItem {
public:
bool new_var;
}
class ExtClass : BaseClass {
protected:
NewItem alpha;
public:
this() {
NewItem temp = new NewItem();
temp.new_var = false;
super(temp);
}
void test_vals() {
if (alpha.some_var) {
writefln("some_var is true");
}
if (alpha.new_var) {
writefln("new_var is true");
}
}
}
int main(char args[][]) {
ExtClass test = new ExtClass();
test.test_vals();
return 0;
}
Apr 15 2008
The problem here is that alpha in ExtClass doesn't override the alpha in=
=
the BaseClass. it just hides it. so Baseclass.alpha is not the same as =
ExtClass.alpha.
You can handle this by casting
class BaseClass {
protected:
SomeItem _alpha;
private:
SomeItem alpha(){ return _alpha; }
public:
this(SomeItem si) {
_alpha =3D si;
si.some_var =3D true;
}
}
class ExtClass : BaseClass {
private:
NewItem alpha(){ return cast(NewItem)_alpha; }
=
public:
this() {
NewItem temp =3D new NewItem();
temp.new_var =3D false;
super(temp);
}
=
void test_vals() {
if (alpha.some_var) {
writefln("some_var is true");
}
=
if (alpha.new_var) {
writefln("new_var is true");
}
}
}
It's not the prettiest way to do it, but it works. Still I'd suggest =
trying a different approach. Perhaps rethink the design.
Cheers,
Boyd
---------
On Tue, 15 Apr 2008 09:20:32 +0200, Chris Williams =
<littleratblue yahoo.co.jp> wrote:
Apr 15 2008
|