C++ Class and object

C++ Object

In C++, an object is a real-world entity that encapsulates both state and behavior. The state represents the data (attributes or properties) of the object, while the behavior represents the functionality (methods or operations) that can be performed on the object. Objects are instances of classes and are created at runtime.

Example:

<#include <iostream>>
<using namespace std;>

class Student {
  public:
    int id;
    string name;

    // Member function to display student details
    void display() {
      cout << "ID: " << id << ", Name: " << name << endl;
    }
};

int main() {
  // Creating an object of Student
  Student s1;

  // Initializing the object
  s1.id = 1;
  s1.name = "John Doe";

  // Calling member function
  s1.display();

  return 0;
}

In this example, Student is a class, and s1 is an object of the Student class. The display function is used to show the object's state.

C++ Class

A class in C++ is a blueprint for creating objects. It defines a set of attributes and methods that the objects created from the class will have. It can include fields (data members), methods (member functions), and constructors.

Example:

<#include <iostream>>
<using namespace std;>

class Student {
  public:
    int id; // Field or data member
    string name; // Field or data member

    // Constructor
    Student(int i, string n) : id(i), name(n) {}

    // Member function to display student details
    void display() {
      cout << "ID: " << id << ", Name: " << name << endl;
    }
};

int main() {
  // Creating an object of Student using parameterized constructor
  Student s1(1, "John Doe");

  // Calling member function
  s1.display();

  return 0;
}

In this example:


Class Student: Defines the attributes (id and name) and methods (display).

Constructor: Initializes the object with id and name.

Object Creation: s1 is an instance of the Student class, created with specific values and using the parameterized constructor.

Key Points

1. Object:

• Represents a specific instance of a class.

• Has attributes (data) and methods (functions).

• Created at runtime.

2. Class:

• A blueprint for creating objects.

• Defines the structure and behavior of objects.

• Can include fields, methods, and constructors.

By using classes and objects, C++ enables organized and modular programming, allowing the design of complex systems through abstraction and encapsulation.