C++ Objects
You can define your own custom data types in C++ using classes. They serve as a guide or model outlining the characteristics (information) and actions (functions) that objects of that kind will have. A class’s name, as well as the names and types of its members, are specified during the definition process.
A variable of a class type is an object. It is sometimes called an instance of the class. Memory is allotted to an object’s data members at creation, and these can be initialized with appropriate values. Objects are produced independently; defining a class just specifies how they will appear. Each class object has a unique copy of the class’s data members, even if they use the same member functions.
Creating Objects (Instances of a Class)
There are multiple methods for creating objects, which are frequently comparable to declaring variables of built-in types:
Direct Declaration (Stack Allocation): As with variables of basic kinds, you can declare objects by using the class name followed by the object name.
- Example: person p; [An example of current chat coding].
- When a variable is declared in this manner (as an automated variable on the stack), its destructor is invoked and the object is destroyed when the variable exits scope.
Dynamic Allocation (Heap/Free Store Allocation) using new: The new operator can be used to allocate objects dynamically. A pointer to the newly formed, nameless object is returned by the new operator.
- If an object has a constructor, it is called when it is dynamically created, and when it is released using delete, its destructor is run.
- Example: Box *myBoxPtr = new Box(); [Example of current discussion code that is comparable to this].
Code Example
#include <iostream> // Required for input/output operations (e.g., std::cout, std::cin)
#include <string> // Required for using std::string
// 1. Define a Class: This is the blueprint
class Car {
public: // Access specifier: Members declared here are accessible from outside the class
// Data Members (Attributes/Properties of a Car)
std::string brand;
std::string model;
int year;
int speed;
// Member Functions (Behaviors/Actions a Car can perform)
// Constructor: A special member function called automatically when an object is created.
// It's used to initialize the object's data members.
Car(std::string b, std::string m, int y) {
brand = b;
model = m;
year = y;
speed = 0; // Initialize speed to 0 by default
std::cout << "A new " << brand << " " << model << " object has been created!" << std::endl;
}
// Function to accelerate the car
void accelerate(int amount) {
speed += amount;
std::cout << "The " << model << " is now accelerating. Current speed: " << speed << " km/h" << std::endl;
}
// Function to brake the car
void brake(int amount) {
speed -= amount;
if (speed < 0) {
speed = 0; // Speed cannot go below zero
}
std::cout << "The " << model << " is braking. Current speed: " << speed << " km/h" << std::endl;
}
// Function to display car information
void displayInfo() {
std::cout << "\n--- Car Information ---" << std::endl;
std::cout << "Brand: " << brand << std::endl;
std::cout << "Model: " << model << std::endl;
std::cout << "Year: " << year << std::endl;
std::cout << "Current Speed: " << speed << " km/h" << std::endl;
std::cout << "-----------------------" << std::endl;
}
}; // Don't forget the semicolon after the class definition!
// Main function where the program execution begins
int main() {
// 2. Create Objects (Instances of the Car Class)
// Creating the first Car object: myCar
// The constructor is called here with arguments.
Car myCar("Toyota", "Camry", 2022);
// Accessing data members and calling member functions for 'myCar' object
myCar.displayInfo();
myCar.accelerate(50);
myCar.accelerate(30);
myCar.brake(20);
myCar.displayInfo();
std::cout << "\n----------------------------------\n" << std::endl;
// Creating a second Car object: yourCar
Car yourCar("Honda", "Civic", 2024);
// Accessing data members and calling member functions for 'yourCar' object
yourCar.displayInfo();
yourCar.accelerate(70);
yourCar.brake(30);
yourCar.displayInfo();
// You can also directly access public data members, but it's generally
// better practice to use member functions for data manipulation (encapsulation).
// yourCar.speed = 100; // This is possible because 'speed' is public
return 0; // Indicate successful program execution
}
Output
A new Toyota Camry object has been created!
--- Car Information ---
Brand: Toyota
Model: Camry
Year: 2022
Current Speed: 0 km/h
-----------------------
The Camry is now accelerating. Current speed: 50 km/h
The Camry is now accelerating. Current speed: 80 km/h
The Camry is braking. Current speed: 60 km/h
--- Car Information ---
Brand: Toyota
Model: Camry
Year: 2022
Current Speed: 60 km/h
-----------------------
----------------------------------
A new Honda Civic object has been created!
--- Car Information ---
Brand: Honda
Model: Civic
Year: 2024
Current Speed: 0 km/h
-----------------------
The Civic is now accelerating. Current speed: 70 km/h
The Civic is braking. Current speed: 40 km/h
--- Car Information ---
Brand: Honda
Model: Civic
Year: 2024
Current Speed: 40 km/h
-----------------------
Constructors and Object Initialization
Whenever an object of a class type is formed, constructors special member functions are automatically run. Setting up the new object’s data members is their main responsibility.
- Constructors are named after their classes and have no return type.
- A class may have many constructors with different parameters to initialise instances. This is known as overloading constructors.
- The compiler frequently provides a default constructor in cases when no explicit constructor is defined. By default, a constructor doesn’t accept any input.
- The values in parenthesis that are used to initialize an object are supplied as arguments to a corresponding constructor. A compile-time error happens if no appropriate constructor can be identified.
- When one object is initialized by another object of the same type, copy constructors a particular kind of overloaded constructor are employed. Unless a special copy constructor is supplied, C++ initializes by performing a bitwise copy.