Basic Class Program in C++
C++ is an object-oriented programming language, and a key concept in OOP is the class. A class acts as a blueprint for creating objects. It defines the data and methods that an object of that class will have.
Here's a basic example of a class program in C++:
#include
using namespace std;
// Define the class
class Rectangle {
private:
int width;
int height;
public:
// Constructor
Rectangle(int w, int h) {
width = w;
height = h;
}
// Member function to calculate area
int getArea() {
return width * height;
}
};
int main() {
// Create an object of the Rectangle class
Rectangle rect1(5, 10);
// Access the member function to calculate area
int area = rect1.getArea();
// Print the area
cout << "Area of the rectangle: " << area << endl;
return 0;
}
Explanation:
-
Class Definition:
class Rectangle { ... };
defines a class calledRectangle
.
-
Private and Public Members:
private:
section:int width;
andint height;
are data members that represent the width and height of the rectangle. These are private, meaning they can only be accessed from within the class itself.
public:
section:- The constructor
Rectangle(int w, int h)
initializes thewidth
andheight
data members when aRectangle
object is created. - The member function
int getArea()
calculates and returns the area of the rectangle.
- The constructor
-
Object Creation:
Rectangle rect1(5, 10);
creates an object calledrect1
of theRectangle
class. The constructor is automatically called with arguments 5 and 10, initializing the width and height.
-
Accessing Member Function:
int area = rect1.getArea();
calls thegetArea()
function on therect1
object to calculate its area, which is stored in thearea
variable.
-
Output:
cout << "Area of the rectangle: " << area << endl;
prints the calculated area of the rectangle.
Key Points:
- Classes act as blueprints for objects.
- Objects are instances of a class.
- Classes have members:
- Data members: Store information.
- Member functions: Perform actions.
- Data members can be declared as
private
(accessible only within the class) orpublic
(accessible from outside the class). - Constructors are special member functions that initialize an object when it is created.
This is a very basic example, but it demonstrates the fundamental principles of using classes in C++. You can build upon this foundation to create complex and sophisticated programs using classes.