Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Base b=new Derived();

 
Vaibhav Shridish
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are these statements the same (the inheritance
heirarchy is self explainatory)?
Statement 1)
============
Base b=new Base()
Derived d=new Derived();
b=d;
Statement 2)
============
Base b=new Derived();
Now in the above statement-2 which object does b
refers to Base or Derived ?
Thanks in advance
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
b would refer to a Derived object (in both cases).
Corey
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vaibhav Shridish:
Are these statements the same (the inheritance
heirarchy is self explainatory)?

Well, almost but not quite the same.

Statement 1)
============
Base b=new Base()
Derived d=new Derived();
b=d;

The above code actually creates two objects, a Base, and a Derived. After the line "b=d" is called, the Base object reference is lost and becomes eligible for garbage collection, and you end up with a Base reference variable pointing to a Derived object.


Statement 2)
============
Base b=new Derived();
Now in the above statement-2 which object does b
refers to Base or Derived ?

Well, clearly you are creating a Derived, and assigning it to a reference variable of type Base; since Base is a superclass of Derived, this is legal (and the quintessential example of polymorphic assignment.) Unlike the first example though, you are NOT creating a Base object.
[ June 06, 2002: Message edited by: Rob Ross ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic