Object-oriented programming (OOP) is a programming paradigm that allows you to create objects, which are instances of classes. C++ is a powerful programming language that fully supports object-oriented programming.
In OOP, you define classes to represent entities in your program. Each class can have data members (attributes) and member functions (methods) that operate on the data members. The data members are usually private, meaning they can only be accessed within the class, while the member functions are public, meaning they can be called from outside the class.
Here's an example of a simple class in C++:
1#include <iostream>
2using namespace std;
3
4// Define a class
5
6class Rectangle {
7 private:
8 int width;
9 int height;
10 public:
11 // Constructor
12 Rectangle(int w, int h) {
13 width = w;
14 height = h;
15 }
16 // Method to calculate area
17 int calculate_area() {
18 return width * height;
19 }
20};
21
22int main() {
23 // Create an object of the Rectangle class
24 Rectangle rect(5, 7);
25
26 // Call the calculate_area method
27 int area = rect.calculate_area();
28
29 // Output the area
30 cout << "The area of the rectangle is: " << area << endl;
31
32 return 0;
33}
This code defines a class Rectangle
with width
and height
as private data members and a calculate_area()
method that returns the area of the rectangle. In the main()
function, we create an object of the Rectangle
class and call the calculate_area()
method to calculate the area of the rectangle.
Output:
1The area of the rectangle is: 35
xxxxxxxxxx
}
using namespace std;
// Define a class
class Rectangle {
private:
int width;
int height;
public:
// Constructor
Rectangle(int w, int h) {
width = w;
height = h;
}
// Method to calculate area
int calculate_area() {
return width * height;
}
};
int main() {
// Create an object of the Rectangle class
Rectangle rect(5, 7);
// Call the calculate_area method
int area = rect.calculate_area();
// Output the area