What do you mean by the term class object? What is the relation (syntax) to access object in C++? Write an example and identify in brief.


Q.) What do you mean by the term class object? What is the relation (syntax) to access object in C++? Write an example and identify in brief.

Subject: Object Oriented Programming and Methodology

Class Object in C++

A class object in C++ is an instance of a class. It is a data structure that contains the data members and member functions of the class. A class object can be created using the new operator. The syntax for creating a class object is:

ClassName *objectName = new ClassName();

For example, the following code creates a class object named myObject of the class MyClass:

class MyClass {
public:
  int x;
  int y;
};

int main() {
  MyClass *myObject = new MyClass();
  myObject->x = 10;
  myObject->y = 20;
  return 0;
}

Accessing Objects in C++

To access the data members and member functions of a class object, we use the . operator. The syntax for accessing the data members of a class object is:

objectName.dataMemberName;

For example, the following code accesses the x data member of the myObject object:

int x = myObject->x;

The syntax for accessing the member functions of a class object is:

objectName.memberFunctionName();

For example, the following code calls the print() member function of the myObject object:

myObject->print();

Example

The following code shows how to create a class, create an object of the class, and access the data members and member functions of the object:

#include 
using namespace std;

class MyClass {
public:
  int x;
  int y;

  void print() {
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
  }
};

int main() {
  MyClass myObject;
  myObject.x = 10;
  myObject.y = 20;
  myObject.print();
  return 0;
}

Output:

x = 10
y = 20