Skip to main content
Engineering LibreTexts

13.2: Classes and Objects

  • Page ID
    29116
  • C++ Classes and Objects

    Class: A class in C++ is the building block, that leads to Object-Oriented programming. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A C++ class is like a blueprint for an object.

    For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of them will share some common properties like all of them will have 4 wheelsSpeed LimitMileage range etc. So here, Car is the class and wheels, speed limits, mileage are their properties.

    An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.

    Defining Class and Declaring Objects

    A class is defined in C++ using keyword class followed by the name of class. The body of class is defined inside the curly brackets and terminated by a semicolon at the end.

    include <iostream>
    using namespace std;
    
    // "class" is a resevered word in C++
    // Junk is a user-defined name for this class definition
    class Junk
    {
        // Access specifier - other specifiers are: private, and protected
        public:
             // Data Members - these are public variables
             string junkName;
             int id;
      
            // Member Functions() - this function is ALSO public
            void printName()
            {
               cout << "My name is: " << junkName;
            }
    };
    

    We will talk about the Public keyword in a moment.

    Declaring Objects: When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects. THIS IS AN IMPORTANT CONCEPT. The class definition simply defines what a class looks like. It is the object declaration that actually allocates memory space by assigning that space to the objectName - which is simply a variable.

    Syntax:

    ClassName objectName;

    Using the class Junk that was defined in the example above, to create an instance of that class we use:

    int main() {
          
        Junk myObj;
        myObj.junkName = "Antique";
        myObj.id=15;
    }
    

    In this code the declaration Junk myObj; declares the variable name myObj to point to an instance of the Junk class. The system allocates enough memory to contain an entire copy of the class Junk, as defined in the previous example. This gets a bit more complex since we have member functions, not simply regular typed varialbes.

    Adapted from:
    "Access Modifiers in C++" by Abhirav Kariya and Harsh Agarwal , Geeks for Geeks 
    "C++ Classes and Objects" by BabisSarantoglouGeeks for Geeks is licensed under CC BY-SA 4.0