C++ Classes and Objects

In C++, classes are user-defined data types that act as blueprints for creating objects. Classes encapsulate data (attributes) and functions (methods) that operate on that data, enabling object-oriented programming concepts like encapsulation, inheritance, and polymorphism.

Syntax

class ClassName {
public:
    // Attributes (data members)
    data_type attribute1;
    data_type attribute2;

    // Methods (member functions)
    return_type methodName(parameters) {
        // code
    }
};

int main() {
    ClassName objectName; // Creating an object
}

Example: Simple Class and Object

#include <iostream>
using namespace std;

class Student {
public:
    string name;
    int age;

    void display() { // Member function
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {

    Student s1;       // Create object s1
    s1.name = "Alice";
    s1.age = 20;

    Student s2;       // Create object s2
    s2.name = "Bob";
    s2.age = 22;

    s1.display();     // Access member function
    s2.display();

    return 0;
}

Output

Name: Alice, Age: 20
Name: Bob, Age: 22

Key Points

  • Class defines the structure and behavior of objects.
  • Object is an instance of a class.
  • Data members store the state of an object, while member functions define its behavior.
  • Access specifiers like public, private, and protected control the visibility of members.

Next Topic

Next, learn about Constructors in C++.