Posts

Showing posts with the label Delphi

Diamond Problem in Multiple Inheritance in OOPS

Image
The diamond problem occurs when two super classes of a class have a common base class.  Suppose there are four classes A, B, C and D. Class B and C inherit class A. Now class B and C contains one copy of all the functions and data members of class A. Class D is derived from class B and C. Now class D contains two copies of all the functions and data members of class A. One copy comes from class B and another copy comes from class C. Let’s say class A has a function with name display(). So class D have two display() functions as I have explained above. If we call display() function using class D object then ambiguity occurs because compiler gets confused that whether it should call display() that came from class B or from class C. If you will compile above program then it will show error. This kind of problem is called diamond problem as a diamond structure is formed (see the image). That is why major programming languages like C#, Java and Delphi don't have multiple inheritanc...

How to declare Static/Class variables, properties, functions and procedures in Delphi?

In Delphi, we do have static variables, properties, functions and procedures, but instead of the word "static" we refer the word "class". In this tutorial, I have shown the syntax of declaring the static variables, properties, functions and procedures in Delphi. We don't have to use "static" keyword while declaring the static variables and properties, just use "class" keyword. While declaring static functions and procedures, we have to use both "class" and "static" keyword. Declare a static/class variable in Delphi type   TStaticDemoClass = class(TObject)   public     class var StaticVar: integer;   end; Declare a static/class property in Delphi type   TStaticDemoClass = class(TObject)   private     class var FStaticVar: integer;   public     class property StaticVar: integer read FStaticVar write FStaticVar;   end; Now we can use above StaticVar variable/property anywhere in the unit like this: procedure TForm1.Button1C...

VCL Hierarchy in Delphi: Types of Controls in Delphi: TWinControls and TGraphicControls

Image
In VCL (Visual Component Library) hierarchy, you will find TObject at the top, then TPersistent, then TComponent and then TControl. TObject >> TPersistent >> TComponent >>TControl VCL Hierarchy in Delphi TObject is the base class from which all classes descend. TPersistent class descends directly from TObject. The special characteristic of TPersistent is that it is an abstract class that defines the methods that allow it to be streamed. TComponent is the base class from which all components descend. Non-visual components are descendants of TComponent. For example: TTimer TControl is the base class from which all the visual components descend. For example: TEdit, TListBox, TComboBox etc. Again, there are two types of controls (TControl): Window Controls (TWinControl) and Graphic Controls (TGraphicControl) Following is the difference between TWinControl and TGraphicControl in Delphi: TWinControls TWinControls can receive input focus and they can be parents to other cont...

Difference between Free and FreeAndNil in Delphi: What to use when?

Difference between Free and FreeAndNil in Delphi: What to use when? Free and FreeAndNil are the main concepts of memory management in Delphi. FreeAndNil is a function declared in the SysUtils unit and was introduced in Delphi 5. Below is the implementation of FreeAndNil: procedure FreeAndNil(var Obj); var   Temp: TObject; begin   Temp := TObject(Obj);   Pointer(Obj) := nil;   Temp.Free; end; Difference between Free and FreeAndNil:  FreeAndNil first sets the object reference to nil and then frees the object.  When to use FreeAndNil instead of Free? If you want a rational answer, the question to ask is, why would you want to set an object reference to nil once you’re done with it?  And there’s only one good reason to ever do that: If you want to reuse the variable later.  There are some times when you’ll have an object that may or may not be initialized. If it’s not, then the variable will be nil, and if you find it’s nil, then you create it before...

Difference between Override and Reintroduce in Delphi

Difference between Override and Reintroduce in Delphi When you decide to declare a method as virtual, you are giving permission to derived classes to extend and override the method with their own implementation. Use the reintroduce keyword to introduce a new implementation of a parent method (this hides the parent method). You can hide a method without using reintroduce but you will get a compiler warning. Using reintroduce will suppress the warning. You tell the compiler that you know that you hide the ancestor function and replace it with this new function and do so deliberately. Difference between Override and Reintroduce 1. The reintroduce and override modifiers have different meanings. The reintroduce modifier creates a new member with the same name, signature, and visibility and hides the original member. The override modifier extends the implementation for an inherited member and allows you to implement inheritance-based polymorphism. 2. Override is used in conjuction with Virtu...

Difference between Virtual, Dynamic and Abstract methods in Delphi

Difference between Virtual, Dynamic and Abstract methods in Delphi Virtual and Dynamic methods are the strong concepts of Polymorphism in Delphi. Dynamic is semantically equivalent to Virtual. Both Virtual and Dynamic directives allows a class method to be override (replaced) by a same named method in a derived class.  You would mark a function or procedure as Virtual or Dynamic when you allow a programmer who creates a class based on your class to replace its functionality.  Virtual and Dynamic may be followed by the Abstract directive. This modifies the effect of the Virtual and Dynamic directives. It means that the current class must not code the method - it is there only as a placeholder to remind and ensure that derived classes implement it. Difference between Virtual and Dynamic methods in Delphi Although Virtual and Dynamic methods appear same but there is some differnce in their internal implementation. Virtual methods are implemented with a Virtual Method Table (VMT)....

Difference between Owner and Parent in Delphi

Difference between Owner and Parent in Delphi Parent is the Window control where the control is displayed. Owner is the component responsible for making sure it's destroyed. Parent refers to the component that another component is contained in, such as TForm, TGroupBox or a TPanel. If one control (parent) contains others, the contained controls are child controls of the parent. Example of Owner and Parent Whenever we try add a button on a panel in a form, we try to make an invisible connection between the components.  When a component is dropped on a form at design time, the owner is the form and the parent is the container on which it is dropped. As we add the button on the panel, the panel automatically is set as the parent of the button while the form becomes the owner.   Another example, drop a group box on a form. Its owner and parent are both the form. Drop a check box on the group box. Its owner is the form and its parent is the group box. Parent is required to make a c...

Difference between Components and Controls in Delphi

Difference between Components and Controls in Delphi Controls are the visible elements on the Delphi Forms to which you can focus and interact. All the controls are components and vice versa is not true. So we can say that Controls are the subset of Components in Delphi. TComponent is the common ancestor of all component objects in Delphi. TControl is the abstract base class for all visual components. Everything that goes into the component palette is a Component. Everything that goes into the component and is something that the user of the program can control by using mouse or keyboard is a Control. For example: TTimer component is a component that you can place on a form, but it is not visible to the end-user. So TTimer is only the component but not a control in Delphi. Other examples like TTimer are TXMLDocument , TDatabase , TQuery , TTable , TDataSet , TDataSource etc. These all components play a vital role but never appear in front of the end user. A TEdit or TButton is visible...

How to create and extract ZIP files in Delphi XE6?

How to create and extract ZIP files in Delphi XE6? Delphi provides System.Zip unit for creating ZIP files. System.Zip unit contains a simple ZIP extractor and creator class named TZIPFile . TZIPFile class mainly has three methods which are used to create and extract zip files: ZipDirectoryContents : Creates the zipped file IsValid : Validates the zip file ExtractZipFile : Extracts the zip file Following is the code snippet in Delphi to create a zip file. uses System.Zip; TZIPFile.ZipDirectoryContents('C:\FolderToZip', 'C:\ZippedFolder.zip'); Following is the code snippet in Delphi to extract a zip files.  uses System.Zip; ZipFile := 'ZippedFolder.zip'; //This is my zip file if TZipFile.IsValid(ZipFile) then //Validate zip file begin   TZipFile.ExtractZipFile(ZipFile, 'C:\DestinationDirectory'); //Extract the zip file end else begin   ShowMessage('Zip File is not valid'); end;

How to create XML document in Delphi XE4 using IXMLDOCUMENT and IXMLNODE?

How to create XML document in Delphi XE4 using IXMLDOCUMENT and IXMLNODE? Following is the self explanatory code in Delphi XE4 to create XML document using IXMLDOCUMENT and IXMLNODE interfaces. You should have XMLIntf and XmlDoc units in your uses section. Following CreateXMLinDelphi Delphi procedure creates an XML named MyXML in D drive. procedure CreateXMLinDelphi; var   XML : IXMLDOCUMENT;   RootNode, CurNode : IXMLNODE; begin   XML := NewXMLDocument;   XML.Encoding := 'UTF-8';   XML.Options := [doNodeAutoIndent];   RootNode := XML.AddChild('ParentNode');   CurNode := RootNode.AddChild('ChildNode1');   CurNode.Text := 'ChildNode Text 1';   CurNode := RootNode.AddChild('ChildNode2');   CurNode.Text := 'ChildNode Text 2';   XML.SaveToFile('D:\MyXML.xml');   ShowMessage('XML created successfully'); end; The above code generates following XML document: <?xml version="1.0" encoding="UTF-8"?> <Par...

How to create an XTR file from XML in Delphi XE4 using XML Mapper?

Image
How to create an XTR file from XML in Delphi XE4 using XML Mapper? By using Delphi XE4 RAD Studio, you can create an XTR file from the given XML file using XML Mapper. XML Mapper Tool is provided in RAD Studio XE4 under Tools -> XML Mapper. Following are the steps to create an XTR file from XML in Delphi XE4 using XML Mapper: 1. Open the XML Mapper Tools from RAD Studio.  Now load an XML. In my case I am loading following simple XML: <?xml version="1.0" encoding="UTF-8"?> <Parent>   <Child1>ABC</Child1>   <Child2>XYZ</Child2> </Parent> All the nodes will appear on the left section of XML Mapper. 2. Right click on left section and select " Select All Children " option. Transformation will be created on the middle section. 3. Right click on left section again and select " Create Datapacket from XML ". You will see the generated datapacket on the right section of the XML Mapper. 4. Hit " Create ...

EOleException error raised with message catastrophic failure or access is denied in Delphi

EOleException error raised with message catastrophic failure or access is denied in Delphi While calling DLLs from my application using safecall, I was getting EOleException error raised with message catastrophic failure. When I switched to stdcall, I started getting EOleException error raised with message access is denied for some calls. So, I thought to dive deep into the root cause of the error and tried to understand what exactly EOleException is in Delphi? As per documentation: EOleException is the exception class for OLE automation errors that occur in methods or properties of an object. EOleException is the exception class for errors specific to the OLE IDispatch interface. EOleException is raised when an error occurs in the middle of a method call from IDispatch. EOleException is generated when a server receives a failure return value from a property or method that was called with the IDispatch interface Invoke method. When an error occurs, objects invoked through IDispatch can...

Delphi Coding Standards and Guidelines

Delphi Coding Standards and Guidelines Below are some Delphi coding standards and guidelines mentioned which each Delphi developer should take care of. Anybody can code, but neat and clean coding is an art. I have tried to mention some Delphi coding standards and guidelines which I follow everyday. Following list includes use of proper naming convention and indentation, proper exception handling and resource management, usage of proper datatypes etc. 1. Use proper naming convention Use proper naming conventions and provide meaningful names to classes, records, arrays, enumerated types, pointers and other variables so that code readability is maintained and other developers can easily understand your code. 2. Always maintain a clear indentation Always leave two character spaces before writing the child statement. Here is the example. if condition1 then begin     fist statement     second statement end; 3. Declare records/class names prefixed with 'T' character, pointe...

How to Insert/Edit Rows in Firebird Dataset in Delphi using FIBPLUS Components?

How to Insert/Edit Rows in Firebird Dataset in Delphi using FIBPLUS Components? You can insert a row and edit an existing row in firebird dataset in Delphi. I will use FIBPLUS dataset component in Delphi XE4. Just use Insert and Edit procedures for this purpose. First of all create a dataset of type TpFIBDataset. Lets have a look at this very simple example. var dsMyFirebirdDataset : TpFIBDataset; Insert a row in a dataset with dsMyFirebirdDataset do begin Insert; dsMyFirebirdDatasetID.AsInteger := 101; dsMyFirebirdDatasetDESC.AsString := 'Hello'; Post; end; You can also use FieldByName like following: with dsMyFirebirdDataset do begin Insert; FieldByName('ID').AsInteger := 101; FieldByName('DESC').AsString := 'Hello'; Post; end; Similarly, you can edit a record/row in the dataset like following: Edit a row in a dataset With dsMyFirebirdDataset do begin Edit; dsHdwPriceGroupDESC.AsString := 'Hello World'; Post; end; or With ...

How to populate data into dataset from Firebird database in Delphi using FIBPLUS components?

How to populate data into dataset from Firebird database in Delphi using FIBPLUS components? I am using Firebird 2.5.2 database and Delphi XE4. I will be using FIBPlus TpFIBDatabase and TpFIBDataset components to populate data from Firebird database to dataset in Delphi XE4. For this, you have to drag TpFIBDatabase and TpFIBDataset components into your Delphi Form from the Tool Palette. Set various properties of TpFIBDatabase component like DBName, Username, Password and LibraryName to connect to Firebird database. I have written a complete tutorial on this. After successfully creating the database connection, set following properties of TpFIBDataset component: Database : Provide the name of database component (TpFIBDatabase) in Database property. In my case, I have created dbMyDatabase component in my previous article . SQLs : Write the query which you want to run. In my case, I am running following query: SELECT ID, NAME FROM MY_FIREBIRD_TABLE WHERE ID = :ID AND NAME = :NAME; Now, p...

How to create database connection with Firebird in Delphi using FIBPLUS components?

How to create database connection with Firebird in Delphi using FIBPLUS components? I am using Firebird 2.5.2 with Delphi XE4. I will show you how to create a database connection with Firebird database in Delphi XE4 using FIBPLUS component? Just go into the Tool Palette and search for TpFIBDatabase component under FIBPLUS. Drag it into the form and name it. I have given "dbMyDatabase" name to TpFIBDatabase database component. If you see your pas file, a declaration for TpFIBDatabase will look like this: var dbMyDatabase: TpFIBDatabase; Now create a function "ConnectToDatabae" with return type boolean. This function will return true if Firebird database connection is established successfully otherwise false. function TMyForm.ConnectToDatabase : boolean;  begin   result := False;   try     try       with dbMyDatabase do      begin         DBName := 'C:\MyProject\MyDB.FDB'; ConnectParams . UserName := 'S...

How to use Generic TList Class in Delphi?

How to use Generic TList Class in Delphi? TList generic class is used to store a list of various data type variables in Delphi. Below is the simple program to illustrate the concept of TList generic class in Delphi. var   List: TList<Integer>;   FoundIndex: Integer; begin   { Create a new List. }   List := TList<Integer>.Create;   { Add a few values to the list. }   List.AddRange([5, 1, 8, 2, 9, 14, 4, 5, 1]);   writeln('Index of first 1 is ' + IntToStr(List.IndexOf(1)));   writeln('Index of last 1 is ' + IntToStr(List.LastIndexOf(1)));   writeln('Does List contains element 100? ' + BoolToStr(List.Contains(100)));   { Add another element to the list. }   List.Add(100);   writeln('There are ' + IntToStr(List.Count) + ' elements in the list.');   { Remove the first occurrence of 1. }   List.Remove(1);   { Delete a few elements from position 0. }   List.Delete(0);   List.DeleteRange(0, 2); ...