There is this ancient feature called object:

There is this ancient feature called object:

type
TFoo = object
end;

It is some kind of Hybrid between a record and a class. It is treated like a record(allocated on stack, contains only fields you have defined) and allows inheritance like a class. I even have a project i want to start in the near future which will utilize it.

However, in the past people said it might be removed at sometime?
Marco Cantu anything on this topic?

Example:
Imagine you write a wrapper for a c-api. The c-api returns typed handles (HandleA, HandleB). For each set of handles there is a set of operations you can do BUT everything you can do with HandleA can be done with HandleB too(but not vice versa). So you have some kind of Handle-Inheritance. My Idea:

type
THandleA = object
private
Data: Pointer;
public
procedure DoSomething;
end;

THandleB = object(THandleA)
public
procedure SomethingElse;
end;

So when a C-Api function returns HandleA, i declare it as THandleA, and if it returns HandleB i declare it as THandleB.

This way i can operate on the handles like on classes. Since record-helpers do not allow inheritance, this seems to be a good option. And wrapping everything up in classes isn't always the best option(when you now the API is called frequently for a lot of objects and you want to avoid the overhead of wrappers)

Comments

  1. Mason Wheeler  No, polymorphism and inheritance are distinct. You can use inheritance to inherit implementation with no polymorphism at all. Frankly, you have a very limited understanding of C++ as evidenced by your frequency statements on the subject that bear no relation at all to reality.

    ReplyDelete
  2. Duh, thanks Alexander Benikowski​, bad example there. Read that as "use a record in stead, for whatever the difference was". (I'm fairly sure there was one, although apparently I can't remember what it was.)

    ReplyDelete
  3. You can only assign a descendant instance of an old style object to an ancestor variable using pointers. Static instances are not assignment compatible. That aspect is sometimes lost because 'class' instances are always references. The slicing problem is very real, but only really affects objects by value. The TPersistent.Assign/AssignTo pattern is supposed to provide value-type semantics to reference types and help alleviate the slicing problem by getting the developer more involved with how values are copied.

    ReplyDelete

Post a Comment