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
TNotifyType: Defines a method pointer type for event handling.TEngineClass: A simple class demonstrating a basic method.TCarClass:- Private Fields:
FEngine(composition),FOnDrive(event),GCount(class variable),FModel,FSpeed. - Constructors: Overloaded constructors for object creation, including one that creates an internal
TEngineinstance. - Destructor: Overridden to free the composed
FEngineobject, ensuring proper memory management. DriveMethod: 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
TCarinstance. - Assigning an event handler to
OnDrive. - Invoking the
Drivemethod. - Setting and reading the
Speedproperty. - Calling the static
IncCountmethod and accessing the staticCountproperty. - Basic exception handling using a
try...exceptblock. - 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 ofAobjects.- Constructors and Destructor: Increment/decrement
cntupon 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:
BaseClass: Defines a virtual functionf()and a virtual destructor.DerivedClass: Inherits fromBaseand overridesf().- Polymorphism: When a
Derivedobject is pointed to by aBasepointer (Base* b = new Derived;), callingb->f()executes theDerivedversion due to thevirtualkeyword. 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 pointerpstores the memory address of variablev.int& r = v;: A referenceracts as an alias for variablev.- Modifying
rdirectly affectsv, which is then reflected when dereferencingp.
C++ Dynamic Array Management
The Arr class manages a dynamic array:
int* d; size_t n;: A pointerdto 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
Arrobjects. - Destructor: Frees the allocated memory using
delete[] d, preventing memory leaks.
C++ Exception Handling Example
The ex() function demonstrates basic exception handling:
- A
tryblock 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
Aobjects to show static member behavior. - Instantiates
BaseandDerivedobjects to illustrate polymorphism. - Calls
ptrRef()for pointer and reference examples. - Creates an
Arrobject 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.
English with a size of 9.22 KB