Beginner's Guide to Class and Object in C++: Learn the Fundamentals of Object-Oriented Programming. (With Example)





In C++, a class is a user-defined data type that groups data members (variables) and member functions (functions that operate on those variables) into a single entity. The class specifies the blueprint for creating objects of that type.

An object, on the other hand, is an instance of a class. When a class is defined, no memory is allocated for its data members. However, when an object of that class is created, memory is allocated for its data members and any initialization code specified in the class's constructor is executed.

For example, consider the following class definition:

class Rectangle {
  public:
    int width;
    int height;
    int area() {
      return width * height;
    }
};

This defines a rectangle class that has two data members (width and height) and one member function (area()) that calculates the area of the rectangle. To create an object of this class, you would use the following code:

Rectangle rect;

This creates an object rect of type Rectangle. You can then set its width and height data members and call its area() member function:

rect.width = 5;
rect.height = 10;
int area = rect.area();

In summary, a class defines a blueprint for creating objects of a certain type, and an object is an instance of that class that has its own set of data members and member functions.

Here is an example code of class and objects used in a programm:-

#include <iostream>
#include <string>

using namespace std;

// Define a class called Employee with two data members and two member functions
class Employee {
public:
    int id;
    string name;
    void printId() {  // Member function to print the ID
        cout << "ID: " << id << endl;
    }
    void printName() {  // Member function to print the name
        cout << "Name: " << name << endl;
    }
};

int main() {
    // Create an object of the Employee class
    Employee emp;

    // Set the values of the id and name data members of the emp object
    emp.id = 10;
    emp.name = "hello";

    // Call the printName() member function to print the name of the emp object
    emp.printName();

    // Call the printId() member function to print the ID of the emp object
    emp.printId();

    return 0;
}

This code defines a class called Employee with two data members, id and name, and two member functions, printId() and printName(). The main() function creates an object of the Employee class, sets the values of the data members, and then calls the printName() and printId() member functions to output the name and ID of the object, respectively.


Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.