23. What is an object?

By | September 23, 2021
  • In C++, an Object is a real-world entity, for example, chair, car, pen, mobile, laptop, etc.
  • In other words, object is an entity that has state and behavior. Here, state means data, and behavior means functionality.
  • Object is a runtime entity, it is created at runtime.
  • Object is an instance of a class. All the members of the class can be accessed through object.
  • Let’s see an example to create object of student class using s1 as the reference variable.
    Student s1;  //creating an object of Student      
    In this example, Student is the type and s1 i
  • s the reference variable that refers to the instance of Student class.

Create an Object

In C++, an object is created from a class.

To create an object of MyClass, specify the class name, followed by the object name.

To access the class attributes (myNum and myString), use the dot syntax (.) on the object:

Example

Create an object called “myObj” and access the attributes:

class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

int main() {
  MyClass myObj;  // Create an object of MyClass

  // Access attributes and set values
myObj.myNum = 15; 
myObj.myString = “Some text”;

  // Print attribute values
  cout << myObj.myNum << “\n”;
  cout << myObj.myString;
  return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *