Class & Object in C++

Milan Kathiriya
2 min readApr 29, 2024

Class:

  • A class can be defined as a blueprint of the object.
  • It is a collection of objects which act as building blocks.
  • A class contains data members (variables) and member functions. These member functions are used to manipulate the data members inside the class.
  • A class can be considered as a custom data type.

Object:

  • An Object is an instance of a class.
  • An Object can be defined as an entity with a state and behavior, in other words, anything that exists physically in the world is called an object. It can represent a dog, a person, a table, etc.
  • An object is a combination of data and programs representing an entity.
Class & Object

Let’s see the syntax of creating a class:

Syntax of a Class in C++

Here’s a breakdown of the syntax:

  1. class: Keyword used to define a class.
  2. ClassName: Name of the class.
  3. {}: Opening and closing curly braces to enclose the class definition.
  4. Member variables (attributes): Data members of the class, typically private or protected.
  5. public:: Access specifier defining the visibility of members below it as public.
  6. Constructors: Special member functions used for initializing objects of the class. They have the same name as the class and no return type.
  7. ~ClassName(): Destructor, used to release resources when an object is destroyed.
  8. Member functions (methods): Functions defined within the class, typically used to perform operations on the class’s data members.
  9. returnType: Data type of the value returned by member functions.
  10. methodName: Name of the member function.
  11. dataType arg1, dataType arg2, …: Parameters passed to member functions.

Note: In C++, classes can also have private and protected access specifiers, which control the visibility of class members. By default, class members have private visibility.

Let’s see the syntax of creating an object:

class_name object_name;

Example of class and object:

Create a class Student and make two objects.

Thanks for reading this article ❤️

If I got something wrong 🙈, Let me know in the comments. I would like to improve.

Clap 👏 If this article helps you. Add to your 📑 Reading list for future reference.

Connect with me on Linkedin and Github

--

--