Difference Between Object and Class in C++

C++Server Side ProgrammingProgramming

In this post, we will understand the difference between an object and a class with respect to C++ programming language.

Classes in C++

  • It is a building block of code in C++ that helps implement object oriented programming.
  • It is a type that is defined by the user.
  • It holds its own data members and member functions.
  • These data members and member functions can be accessed by creating an instance of the class.
  • They can be used to manipulate the variables and can be used to define property to tell how the objects in a class have to act.
  • It can be understood as a blueprint for an object.
    • Example: Consider the class of Employees. There may be many attributes such as name of employee, age, date of birth, title, and so on.
    • These are called the data members.
    • The member functions could be 'draw_salary', 'get_promotion', which perform certain actions with respect to class objects.
    • These would be the common properties shared by all employees.
  • It is defined using the keyword 'class'.
  • It is followed by the name of the class.
  • The class body is defined within flower brackets, and is terminated using a semi-colon.
class class_name {

Objects in C++

  • An object is an instance of a class.
  • When a class is defined, memory is not allocated to it.
  • The moment an object is created, memory gets allocated to all the attributes of the class.
  • When a class is defined, the specifics of the object are defined.
  • If that class has to be put to use, and operations need to be performed, an object needs to be created.
  • The object has to be explicitly created using the below syntax.
class_name object_name;
  • The data members and member functions of a class can be accessed by an object with the help of the dot ('.') operator.
    • Example: Assume a class has been created with the required attributes and member functions.
    • Once an object with respect to that class is created, the member functions can be accessed in the below way:
  • The data members which are public in nature, can be accessed in the same manner, as shown above, i.e using the '.' operator.
  • Public members are those that are defined using the 'public' keyword.
  • Private members are those that are defined using the 'private' keyword.
  • These members can't be accessed directly by the object.
  • The 'public', 'private' and 'protected' keywords are known as access controls of the data members.
  • Member functions that are defined inside the class are considered to be inline by default.
  • The inline functions ae those which are expanded right after the function is defined. They are copied everywhere when the code is compiled (similar to macros). This means that the overhead of calling the function is reduced.
  • Any non-class function can be made as an inline function by attaching the 'inline' keyword to it.
Published on 02-Mar-2021 09:23:47