including classes and objects, constructors and destructors, inheritance and polymorphism,
encapsulation and data hiding, operator overloading, and virtual functions and abstract
classes:
**4.1 Classes and Objects:**
Classes are the foundation of object-oriented programming. A class is a user-defined data
type that encapsulates data (member variables) and functions (member functions) into a
single entity. Objects are instances of classes.
Here's an example of a class representing a `Person`:
```cpp
class Person {
private:
std::string name;
int age;
public:
void setName(const std::string& newName) {
name = newName;
}
void setAge(int newAge) {
age = newAge;
}
void displayInfo() {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
};
```
To create an object of the `Person` class and access its member functions and variables:
```cpp
Person person1;
person1.setName("John");
person1.setAge(25);
person1.displayInfo();
```
**4.2 Constructors and Destructors:**
Constructors are special member functions that are automatically called when an object is
created. They initialize the object's data members and perform any necessary setup.
Constructors have the same name as the class and no return type.
, ```cpp
class Person {
private:
std::string name;
int age;
public:
// Default constructor
Person() {
name = "";
age = 0;
}
// Parameterized constructor
Person(const std::string& newName, int newAge) {
name = newName;
age = newAge;
}
void displayInfo() {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
};
```
Destructors are special member functions that are automatically called when an object is
destroyed. They clean up resources used by the object, such as freeing dynamically
allocated memory. Destructors have the same name as the class, preceded by a tilde (`~`).
```cpp
class Person {
private:
std::string name;
int age;
public:
// ...
~Person() {
std::cout << "Person object destroyed." << std::endl;
}
};
```
**4.3 Inheritance and Polymorphism:**