In C++, objects are created by instantiating a class, which allocates memory for the object and initializes its data members. Here’s an overview of how to create and use objects in C++:
1. Declare the class: First, you need to declare the class that you want to create objects from. This is done by defining the class in a header file or in the source file before its first use. For example:
class Person { public: string name; int age; double height; void sayHello() { cout << "Hello, my name is " << name << " and I am " << age << " years old." << endl; } };
2. Create the object: To create an object, you need to declare a variable of the class type. For example:
Person p;
In this example, a variable `p` of type `Person` is declared. This allocates memory for an object of the `Person` class and initializes its data members to their default values.
3. Access and modify the data members: You can access and modify the data members of an object using the dot (.) operator. For example:
p.name = "John Smith"; p.age = 30; p.height = 1.8;
In this example, the `name`, `age`, and `height` data members of the `p` object are set to the values "John Smith", 30, and 1.8, respectively.
4. Call the member functions: You can call the member functions of an object using the dot (.) operator. For example:
p.sayHello();
In this example, the `sayHello()` member function of the `p` object is called, which outputs a greeting that includes the `name` and `age` data members.
5. Use the object: Once you have created an object and set its data members, you can use it in your program as needed. For example:
Person p; p.name = "John Smith"; p.age = 30; p.height = 1.8; p.sayHello(); Person *ptr = new Person; ptr->name = "Jane Doe"; ptr->age = 25; ptr->height = 1.6; ptr->sayHello(); delete ptr;
In this example, two objects of the `Person` class are created: `p` and `ptr`. The `name`, `age`, and `height` data members of each object are set to different values, and the `sayHello()` member function is called on each object to output a greeting. The `ptr` object is created using dynamic memory allocation and is accessed using the arrow (->) operator. Finally, the `ptr` object is deleted using the `delete` operator to free the memory it occupies.
By creating and using objects in C++, you can create custom data types that can represent real-world objects or complex data structures. Objects are created by instantiating a class, which allocates memory for the object and initializes its data members. Data members can be accessed and modified using the dot (.) operator, and member functions can be called on the object to perform operations on its data members. Once an object is created, it can be used in your program as needed.