Basic Class Program In C++

4 min read Jul 03, 2024
Basic Class Program In C++

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:

  1. Class Definition:

    • class Rectangle { ... }; defines a class called Rectangle.
  2. Private and Public Members:

    • private: section:
      • int width; and int 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 the width and height data members when a Rectangle object is created.
      • The member function int getArea() calculates and returns the area of the rectangle.
  3. Object Creation:

    • Rectangle rect1(5, 10); creates an object called rect1 of the Rectangle class. The constructor is automatically called with arguments 5 and 10, initializing the width and height.
  4. Accessing Member Function:

    • int area = rect1.getArea(); calls the getArea() function on the rect1 object to calculate its area, which is stored in the area variable.
  5. 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) or public (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.

Featured Posts