Inheritance problem

%u unknown at unknown.com
Fri Feb 11 13:14:31 PST 2011


== Auszug aus Steven Schveighoffer (schveiguy at yahoo.com)'s Artikel
> On Fri, 11 Feb 2011 15:40:18 -0500, %u <unknown at unknown.com> wrote:
> > Hello,
> >
> > I've a problem with my class inheritance. I have class called
Texture
> > which implements the interface IDrawable and the abstract class
> > APickable.
> > The Texture-class contains 3 members which looks like this:
> >
> > GLuint pTextureID;
> >
> > Size pSize1, pSize2;
> >
> > Finally... my Texture-class looks like:
> >
> > class Texture : APickable, IDrawable {
> >    protected {
> >       GLuint pTextureID;
> >       Size pSize, pAnoutherSize;
> >    }
> > }
> >
> > now... I have a second class called Animation which looks like
this:
> >
> > class Animation : Texture {
> >    private {
> >       Texture[] pFrames;
> >    }
> >    public {
> >       this(string file, string[] paths...) {
> >          super(file);
> >          pFrames ~= this;
> >          foreach(string cur; paths) {
> >             pFrames ~= new Texture(cur);
> >          }
> >       }
> >
> >       Size getSize() {
> >          return pFrames[0].pSize;
> >       }
> >    }
> > }
> >
> > As I know, pFrames[0].pSize can be called... pSize in the Texture-
> > class is marked as protected, but I get the following error:
> >
> > Error: class Texture member pSize is not accessible.
> >
> > When I mark the protected members of the Texture-class as public,
it
> > works (should be clear), but why do I get this error when mark
them
> > as protected?
> >
> > I hope anyone can help to solve the problem.
> protected means you cannot access it outside the *instance*.  The
pFrames
> array references *other instances* of Texture, so they are not
accessible.
> http://www.digitalmars.com/d/2.0/attribute.html#ProtectionAttribute
> "If accessing a protected instance member through a derived class
member
> function, that member can only be accessed for the object instance
which
> is the ‘this’ object for the member function call."
> -Steve

Thanks, but what about the following:

import std.stdio : writeln;

class a  {

	public this(int v) {
		myVar = v;
	}

	protected int myVar;

}

class b : a {

	private a[] moreInstances;

	this(int v, int[] vars...) {
		super(v);
		moreInstances ~= this;

		foreach(int cur; vars) {
			moreInstances ~= new a(cur);
		}
	}

	int getVar() {
		return moreInstances[1].myVar;
	}

}

void main(string[] args) {
	b exp = new b(0, 1, 2);
	writeln(exp.getVar());
}

This compiles fine and prints the number 1. myVar is also protected
in class a, I also call myVar in the getVar()-method of class b.


More information about the Digitalmars-d-learn mailing list