Reputation: 35522
If I have child class,the child class inherits all methods from the parent,but how do I use functions from the child class in the parent class? Is that what abstraction is? How do I accomplish it?
My code:
type
cParent = class(TObject)
private
function ParentFunction:byte;
function ChildFunction:byte;virtual;abstract;
end;
type
cChild = class(cParent)
private function ChildFunction:byte;override;
end;
function cChild.ChildFunction:byte;
begin
Exit(20);
end;
function cParent.ParentFunction:byte;
begin
Exit(10);
end;
var
c:cParent;
begin
c:= cParent.Create;
WriteLn(c.ChildFunction);
Readln;
end.
It compiles file,but I get abstraction exception.
Upvotes: 1
Views: 608
Reputation: 1705
In response to schnaader, regarding CS 101:
"virtual" means the method can be overridden by child classes.
Not only this, but non-virtual functions may happily be overridden by child classes. The difference is very important: when a virtual function is called by the parent class, the CHILD function will be executed. This allows child classes to implement functions that will be called by parent classes without the parent ever knowing anything about them. This is the essence of polymorphism.
Upvotes: 0
Reputation: 4415
It seems to me that you have confused inheritance relationships and possessive relationships. If you define a class "cChild" as inherited from class "cParent" then the class "cChild" is a "cParent", it does not mean, that the class "Parent" has access to any child classes. The only way you can call the abstract function "ChildFunction" in the class "cParent" is from another function, e.g. "ParentFunction", but only if the Object itself is not a "cParent":
function cParent.ParentFunction:byte;
begin
Result := ChildFunction * 2;
end;
var
c:cParent;
begin
c:= cChild.Create;
WriteLn(c.ParentFunction);
Readln;
end.
Here, since c is a cChild, ParentFunction correctly calls ChildFunction, which is defined in cChild.
Upvotes: 0
Reputation: 49719
c:= cParent.Create;
WriteLn(c.ChildFunction);
You create an instance of cParent class here. This class does only contain an abstract ChildFunction that can be overridden by other classes. The function is not implemented in cParent, so you get an abstract error.
The code works if you use the cChild class instead, where ChildFunction is implemented:
c:= cChild.Create;
WriteLn(c.ChildFunction);
For clarification, imagine a parent class named GeometricObject
with an virtual abstract method CalculateVolume
. You can now create child classes like SphereObject
or BoxObject
that implement CalculateVolume
by using the formula for spheres/boxes. But it doesn't make sense to create an instance of GeometricObject
and call CalculateVolume
.
Upvotes: 5
Reputation:
You create instance of cParent class. This class don't have implementation of childFunction. c must be instance of cChild class. Correct code: c := cChild.Create; WriteLn(c.ChildFunction);
Upvotes: 2