www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Object "A" inherited object "B". And you need to return the object

reply Mihail Lorenko <miha.uva ya.ru> writes:
Hello!
Interested in a question.
Object "A" inherited object "B". And you need to return the 
object link "B". Is this possible in this language? Here is an 
example:

class B
{
    protected int a;
    public void step() {};
}

class A : B
{
    public override step()
    {
        import std.random;
        a = uniform(5,100);
    }
}

void main()
{
     B* b;
     A  a;
     a.step();
     b = a.B; //  FixMe: Here you need a link to object B from 
 object A.
}
Sorry to trouble you, thanks in advance!
Feb 06 2020
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Thursday, 6 February 2020 at 12:15:17 UTC, Mihail Lorenko 
wrote:
     B* b;
A pointer to a class is a rare thing in B since they are already automatic references. Just use `B b;` and ten `b = a` will just work.
Feb 06 2020
parent reply Mihail Lorenko <miha.uva ya.ru> writes:
On Thursday, 6 February 2020 at 12:37:01 UTC, Adam D. Ruppe wrote:
 On Thursday, 6 February 2020 at 12:15:17 UTC, Mihail Lorenko 
 wrote:
     B* b;
A pointer to a class is a rare thing in B since they are already automatic references. Just use `B b;` and ten `b = a` will just work.
Thanks for the answer! Well, apparently I have to get around my problem. Thanks again!
Feb 06 2020
parent reply Steven Schveighoffer <schveiguy gmail.com> writes:
On 2/6/20 8:05 AM, Mihail Lorenko wrote:
 On Thursday, 6 February 2020 at 12:37:01 UTC, Adam D. Ruppe wrote:
 On Thursday, 6 February 2020 at 12:15:17 UTC, Mihail Lorenko wrote:
     B* b;
A pointer to a class is a rare thing in B since they are already automatic references. Just use `B b;` and ten `b = a` will just work.
Thanks for the answer! Well, apparently I have to get around my problem. Thanks again!
Not sure, but you might misunderstand. B is already a pointer in D (like Java, D's class instances are always references). And derived classes implicitly cast to base classes. So the a.B syntax is not necessary. To illustrate further: A a = new A; // note, instances by default are null, you need to new them B b = a; // implicit cast assert(a is b); // they are the same object b.step(); // virtual call, calls B.step assert(a.a != 0); // note, protected allows access from same module. -Steve
Feb 06 2020
parent Steven Schveighoffer <schveiguy gmail.com> writes:
On 2/6/20 10:11 AM, Steven Schveighoffer wrote
 b.step(); // virtual call, calls B.step
I meant, calls A.step; -Steve
Feb 06 2020