You are on page 1of 9

OBJECT-ORIENTED

PROGRAMMING
CHAPTER
7&8

BY THEISA
Constructors

Syntax: ClassName() { /* Constructor code */ }

Example:

class Rectangle {
public:
int length;
int width;

Rectangle() {
length = 0;
width = 0;
}
};
Destructors

Syntax: ~ClassName() { /* Destructor code */ }

Example:

class Rectangle {
public:
int* arr;

Rectangle() {
arr = new int[10];
}

~Rectangle() {
delete[] arr;
}
};
Function Overriding
 Function overriding is a feature that allows a derived class

to provide a different implementation of a method defined

in its base class.

 It enables a class to inherit and modify the behavior of a

method from its superclass.

 Function overriding promotes code extensibility and enables

the implementation of specialized functionality in derived

classes.
Templates

Function Templates

Syntax:

template <typename T>


returnType functionName(T parameter) {
// Code
}

Example:

template <typename T>


T add(T a, T b) {
return a + b;
}
Class Templates

Syntax:

template <typename T>


class ClassName {
// Code
};

Example:

template <typename T>


class Stack {
private:
T* arr;
int top;

public:
// Code
};
Exception Handling
Try-Catch Block

Syntax:

try {
// Code that might throw an exception
}
catch (ExceptionType& exceptionObject) {
// Code to handle the exception
}

Example:

try {
int result = divide(10, 0);
}
catch (const std::runtime_error& error) {
std::cout << "Exception occurred: " << error.what() <<
std::endl;
}
Exception Handling
Throwing Exceptions

Syntax:

throw ExceptionType("Exception message");

Example:

int divide(int a, int b) {


if (b == 0) {
throw std::runtime_error("Division by zero error");
}
return a / b;
}

You might also like