Subclass->Base->Subclass help

boyd gaboonviper at gmx.net
Tue Apr 15 02:18:16 PDT 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 = si;
  		si.some_var = true;
  	}
   }

  class ExtClass : BaseClass {
  private:
  	NewItem alpha(){ return cast(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");
  		}
  	}
  }

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 at yahoo.co.jp> wrote:

> 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;
> }



-- 
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/


More information about the Digitalmars-d-learn mailing list