Object-Oriented Programming Examples: Delphi and C++
Introduction to OOP Concepts
This document presents practical code examples demonstrating fundamental Object-Oriented Programming (OOP) concepts in both Delphi (Pascal) and C++. It covers class definitions, object instantiation, properties, events, static members, inheritance, polymorphism, memory management, and exception handling.
Delphi Object-Oriented Programming
The following Delphi code illustrates the creation of classes, properties, events, and static members, along with their usage in a console application.
program Cheat;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes;
type
TNotify = procedure(Sender: TObject) of object;
TEngine = class
procedure Start;
begin
Writeln('Engine Started');
end;
end;
TCar = class
private
FEngine: TEngine;
FOnDrive: TNotify;
class var GCount: Integer;
FModel: String;
FSpeed: Integer;
procedure SetSpeed(v: Integer);
begin
FSpeed := v;
end;
protected
public
constructor Create; overload;
constructor Create(E: TEngine); overload;
destructor Destroy; override;
procedure Drive; virtual;
begin
if Assigned(FOnDrive) then
FOnDrive(Self)
else
FEngine.Start;
end;
class procedure IncCount; static;
begin
Inc(GCount);
end;
property Speed: Integer read FSpeed write SetSpeed;
property Count: Integer read GCount;
property OnDrive: TNotify write FOnDrive;
published
property Model: String read FModel write FModel;
end;
constructor TCar.Create;
begin
Create(TEngine.Create);
end;
constructor TCar.Create(E: TEngine);
begin
inherited Create;
FEngine := E;
end;
destructor TCar.Destroy;
begin
FEngine.Free;
inherited;
end;
var
C: TCar;
begin
try
C := TCar.Create;
C.OnDrive := @TCar.Drive;
C.Drive;
C.Speed := 120;
Writeln('Current Speed: ', C.Speed);
TCar.IncCount;
Writeln('Car Count: ', C.Count);
except
on E: Exception do
Writeln('Error: ', E.ClassName, ': ', E.Message);
end;
C.Free;
end.
Delphi Class Definitions and Members
TNotify
Type: Defines a method pointer type for event handling.TEngine
Class: A simple class demonstrating a basic method.TCar
Class:- Private Fields:
FEngine
(composition),FOnDrive
(event),GCount
(class variable),FModel
,FSpeed
. - Constructors: Overloaded constructors for object creation, including one that creates an internal
TEngine
instance. - Destructor: Overridden to free the composed
FEngine
object, ensuring proper memory management. Drive
Method: A virtual method demonstrating event invocation or default behavior.- Static Method (
IncCount
): A class-level method to increment a shared counter (GCount
). - Properties:
Speed
(read/write),Count
(read-only class property),OnDrive
(event property), andModel
(published property).
- Private Fields:
Delphi Program Execution Flow
The main program block demonstrates:
- Creating a
TCar
instance. - Assigning an event handler to
OnDrive
. - Invoking the
Drive
method. - Setting and reading the
Speed
property. - Calling the static
IncCount
method and accessing the staticCount
property. - Basic exception handling using a
try...except
block. - Proper object deallocation using
C.Free
.
C++ Object-Oriented Programming
This C++ code snippet showcases various OOP features, including static members, inheritance, virtual functions, pointers, references, dynamic memory allocation, and exception handling.
#include <iostream>
using namespace std;
// Static member
class A {
static int cnt;
int x;
public:
A(int v = 0) : x(v) { ++cnt; }
A(const A& o) : x(o.x) { ++cnt; }
~A() { --cnt; }
static int getCnt() { return cnt; }
};
int A::cnt = 0;
// Inheritance & virtual
class Base {
public:
virtual void f() { cout << "Base class method\n"; }
virtual ~Base() {}
};
class Derived : public Base {
public:
void f() override { cout << "Derived class method\n"; }
};
// Pointer & reference
void ptrRef() {
int v = 1;
int* p = &v;
int& r = v;
r = 2;
cout << "Value via pointer: " << *p << "\n";
}
// Dynamic array
class Arr {
int* d;
size_t n;
public:
Arr(size_t s) : n(s), d(new int[s]) {}
Arr(const Arr& o) : n(o.n), d(new int[o.n]) {
// Deep copy for dynamic array
for (size_t i = 0; i < n; ++i) {
d[i] = o.d[i];
}
}
~Arr() { delete[] d; }
};
void ex() {
try {
throw runtime_error("An error occurred in C++ example.");
} catch (const exception& e) {
cout << "Caught exception: " << e.what() << "\n";
}
}
int main() {
A a1;
A a2(a1);
cout << "Count of A objects: " << A::getCnt() << "\n";
Base* b = new Derived;
b->f(); // Demonstrates polymorphism
delete b; // Proper cleanup for virtual destructor
ptrRef();
Arr arr(5); // Dynamic array creation
ex(); // Exception handling demonstration
return 0;
}
C++ Static Class Members
The A
class demonstrates static members:
static int cnt;
: A static data member, shared by all objects of classA
. It tracks the number ofA
objects.- Constructors and Destructor: Increment/decrement
cnt
upon object creation/destruction. static int getCnt();
: A static member function to access the static counter.
Inheritance and Virtual Functions in C++
The Base
and Derived
classes illustrate inheritance and polymorphism:
Base
Class: Defines a virtual functionf()
and a virtual destructor.Derived
Class: Inherits fromBase
and overridesf()
.- Polymorphism: When a
Derived
object is pointed to by aBase
pointer (Base* b = new Derived;
), callingb->f()
executes theDerived
version due to thevirtual
keyword. The virtual destructor ensures correct cleanup.
Pointers and References in C++
The ptrRef()
function demonstrates the use of pointers and references:
int* p = &v;
: A pointerp
stores the memory address of variablev
.int& r = v;
: A referencer
acts as an alias for variablev
.- Modifying
r
directly affectsv
, which is then reflected when dereferencingp
.
C++ Dynamic Array Management
The Arr
class manages a dynamic array:
int* d; size_t n;
: A pointerd
to the dynamically allocated array and its sizen
.- Constructor: Allocates memory for the array using
new int[s]
. - Copy Constructor: Performs a deep copy to ensure independent arrays when copying
Arr
objects. - Destructor: Frees the allocated memory using
delete[] d
, preventing memory leaks.
C++ Exception Handling Example
The ex()
function demonstrates basic exception handling:
- A
try
block encloses code that might throw an exception. - A
throw runtime_error(...)
statement generates an exception. - A
catch (const exception& e)
block catches the thrown exception and prints its message usinge.what()
.
C++ Main Function Execution
The main()
function orchestrates the demonstrations:
- Creates
A
objects to show static member behavior. - Instantiates
Base
andDerived
objects to illustrate polymorphism. - Calls
ptrRef()
for pointer and reference examples. - Creates an
Arr
object for dynamic array management. - Invokes
ex()
to demonstrate exception handling.
Conclusion
These code examples provide a foundational understanding of key Object-Oriented Programming concepts in both Delphi and C++. By comparing their implementations, developers can appreciate the similarities and differences in how these powerful paradigms are applied across different programming languages.