-1

There are two classes:

class A
{
   protected IntPtr i;
   public A(A copy)
   {
      this.i = SomeStaticClass.Copy(copy.i);
   }
   protected A(IntPtr ds)
   {
      this.i = ds;
   }
}

class B : A
{
    public B(A init)
    {
        SomeStaticClass.doSomethingWith(init.i); //Cant access this field.
    }

    public void AnotherMethod(A asd)
    {
        SomeStaticClass.doSomethingWith(init.i); //Cant access this field again.
    }
}

Field "i" in A class may controll the unmanaged code, so it's should'nt be public.

And I dont wanna make a copy of A (whinch gonna call some unmanaged code to copy i field, whinch is taking some time), this constructor of B is just converting A to B.

Why do objects of class B cant access objectOfA.i field?

Is there any way to fix that problem?

PsyWhat
  • 55
  • 5

2 Answers2

1

What about this?

class B : A
{
    public B(A init) 
        : base(init)
    {
        SomeStaticClass.doSomethingWith(i);
    }

    public void AnotherMethod(A asd)
    {
        SomeStaticClass.doSomethingWith(i);
    }
}

B needs to call A's constructor and then the protected member i is set. You can then access this protected field in the derived class as usual.

I need to access init.i, not a this.i

You can't for obvious reasons. A protected member is accessible within its class and by derived class instances only: msdn.microsoft.com/en-us/library/bcd5672a.aspx

mm8
  • 163,881
  • 10
  • 57
  • 88
  • I need to access init.i, not a this.i, bro – PsyWhat Mar 21 '17 at 22:34
  • You can't for obvious reasons; a protected member is accessible *within* its class and by *derived* class instances: https://msdn.microsoft.com/en-us/library/bcd5672a.aspx – mm8 Mar 21 '17 at 22:42
-1

If you want to construct B object using A object, then you need to call A constructor first and then you can access to i using this in B object. In your B constructor, call your base (A) constructor.

Then you can call:

SomeStaticClass.doSomethingWith(this.i);
Ricardo Serra
  • 374
  • 2
  • 11