Home Tutorials C++ Tutorial Classes and Objects
Classes and Objects

Classes and Objects


C++ Classes and Objects

Definition: In C++, a Class is a user-defined data type that acts as a blueprint or template for creating objects. An Object is a specific instance of that class. If a class is the architectural drawing of a house, the object is the actual house built from those drawings.

Why: Classes and objects are the fundamental building blocks of Object-Oriented Programming. They allow you to group data (attributes) and functions (methods) into a single logical unit, making code more organized, scalable, and easier to manage as projects grow in complexity.


The Blueprint vs. The Instance

A class defines what data an object will hold and what it can do, but it does not occupy memory until an object is created from it.

Entity Role
Class The logical definition or template (e.g., Student).
Object The physical reality in memory (e.g., s1).

Example: Creating a Student Instance

In this example, we define a Student class with two public attributes and then create an object s1 to store specific information:

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

// Defining the Class (The Blueprint)
class Student {
  public:          // Access specifier: members are accessible from outside
    string name;   // Attribute (variable)
    int age;       // Attribute (variable)
};

int main() {
    // Creating an Object of Student (The Instance)
    Student s1;

    // Accessing attributes using the dot operator (.)
    s1.name = "Ravi";
    s1.age = 20;

    cout << "Student Name: " << s1.name << endl;
    cout << "Student Age: " << s1.age << endl;

    return 0;
}

Key Notes

  • The public Keyword: In C++, the public access specifier is mandatory if you want to access class members from outside the class (like in main()). By default, all members of a class are private.
  • Dot Operator (.): This is the standard syntax for accessing an object's variables or functions. You use objectName.memberName.
  • Multiple Objects: You can create many objects from a single class (e.g., Student s1, s2, s3;). Each object has its own unique copy of the attributes; changing s1.name does not affect s2.name.
  • Class vs. Struct: While they look similar, the technical difference is that struct members are public by default, whereas class members are private by default. Classes are preferred when building complex logic with data protection in mind.

🏋️ Test Yourself With Exercises

Take our quiz on Classes and Objects to test your knowledge.

Browse Quizzes »