CPP Tutorial



C++ CLASSES/OBJECTS


Classes and Objects in C++

Classes and objects are the foundation of Object-Oriented Programming in C++. A class is like a blueprint for creating objects. An object is an instance of a class, containing real values instead of placeholders.

🧠 Think of it like this:
Class = Design Plan → Object = Actual Product built using that plan

🧱 Defining a Class

A class in C++ is defined using the class keyword. It can have data members (variables) and member functions (methods).

📄 Example: Class and Object

#include <iostream>
using namespace std;

// Class definition
class Student {
  public:
    string name;
    int age;

    void introduce() {
      cout << "Hi, I am " << name << " and I am " << age << " years old." << endl;
    }
};

int main() {
  Student s1;              // Object creation
  s1.name = "Rahul";
  s1.age = 18;
  s1.introduce();          // Method call

  return 0;
}
  

🖨️ Output:

Hi, I am Rahul and I am 18 years old.

🔍 Explanation

  • class Student defines a template for student data.
  • name and age are data members (attributes).
  • introduce() is a member function (method) of the class.
  • s1 is an object of the class Student.
  • s1.name = "Rahul" assigns values to the object’s data members.

👀 Access Specifiers

Access specifiers define who can access the class members:

  • public: Accessible from outside the class.
  • private: Accessible only inside the class (default).
  • protected: Accessible inside the class and by derived classes.

🏗️ Multiple Objects

You can create multiple objects from one class:

Student s1, s2;
s1.name = "Amit";
s2.name = "Priya";
  

🎓 Conclusion

Classes are user-defined data types, and objects are variables of that type. This structure brings modularity, clarity, and reuse to your code — making C++ powerful for real-world applications.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review