C++ Class and Object

In C++, classes and objects are fundamental concepts of Object-Oriented Programming (OOP).

class

A class is a blueprint or template for creating objects. It defines properties (attributes) and behaviors (methods or functions) that the objects created from the class will have.

Properties (Attributes): Variables that hold the data or state of the object.

Methods (Functions): Functions that define the behavior of the object, i.e., what it can do.

Object

An object is an instance of a class. When you create an object from a class, you can access and modify its properties and call its methods.

Example of Class and Object:


#include <iostream>
#include <string> // For using the string type
using namespace std;

// Define a class called 'Employee'
class Employee {
public:
    // Properties (Attributes)
    string firstName;
    string lastName;
    int age;

    // Method (Function)
    void displayFullName() {
       cout << "Full Name: " <<  firstName << " " <<  lastName << endl;
       cout << "Emp's age " << age << endl;
    }
};

int main() {
    // Create an object of the class 'Employee'
    Employee emp;
    
    // Set properties (attributes)
    emp.firstName = "John";
    emp.lastName = "Taylor";
    emp.age = 35;

    // Call method (function)
    emp.displayFullName(); 

    return 0;
}

Output:

Full Name: John Taylor
Emp's age 35