www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - is this a poly Polymorphism?

reply hhaammaadd <h.battel hotmail.com> writes:
import std.stdio;
class employee {
         void work() {
                 writeln("I am employee");
         }
}

class manager: employee {
         void work() {
                 writeln("I am manager");
                 }
}


void main() {
         employee e1 = new manager;//here
         e1.work();

         manager m3 = new manager;//--|here
         employee *e2 = &m3;//--------|
         e2.work();


}
Aug 28 2011
parent reply Jonathan M Davis <jmdavisProg gmx.com> writes:
On Monday, August 29, 2011 04:50:09 hhaammaadd wrote:
 import std.stdio;
 class employee {
          void work() {
                  writeln("I am employee");
          }
 }
 
 class manager: employee {
          void work() {
                  writeln("I am manager");
                  }
 }
 
 
 void main() {
          employee e1 = new manager;//here
          e1.work();
 
          manager m3 = new manager;//--|here
          employee *e2 = &m3;//--------|
          e2.work();
 
 
 }
Pointers are not polymorphic in D. Class references are, but if you have a pointer to a class, it assumes that the type is exactly that type and determines its function calls at compile time rather than at runtime. - Jonathan M Davis
Aug 28 2011
parent Michel Fortin <michel.fortin michelf.com> writes:
On 2011-08-29 01:58:30 +0000, Jonathan M Davis <jmdavisProg gmx.com> said:

 On Monday, August 29, 2011 04:50:09 hhaammaadd wrote:
 import std.stdio;
 class employee {
 void work() {
 writeln("I am employee");
 }
 }
 
 class manager: employee {
 void work() {
 writeln("I am manager");
 }
 }
 
 
 void main() {
 employee e1 = new manager;//here
 e1.work();
 
 manager m3 = new manager;//--|here
 employee *e2 = &m3;//--------|
 e2.work();
 
 
 }
Pointers are not polymorphic in D. Class references are, but if you have a pointer to a class, it assumes that the type is exactly that type and determines its function calls at compile time rather than at runtime.
Actually, a pointer to a class is really a pointer to a reference to an object, since the reference is always with a class type. So "employee *" is in reality a pointer to a reference to an employee object. -- Michel Fortin michel.fortin michelf.com http://michelf.com/
Aug 29 2011