Welcome to another engaging lesson at CodeYourCraft! Today, we're diving deep into the world of C++, focusing on Object Creation. Let's get started! šÆ
In C++, an object is an instance of a class. It's a real-world entity that encapsulates data and functions related to that entity. For example, a Car object might have attributes like color, model, and speed, and methods like accelerate() and brake().
To create an object, we first need to define a class, then create an instance of that class. Here's a simple example of a Person class and its instance:
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
// Constructor
Person(string n, int a) {
name = n;
age = a;
}
// Print Person details
void printDetails() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
Person person1("John", 25); // Creating an object of Person class
person1.printDetails(); // Calling the printDetails() method
return 0;
}In the code above, we define a Person class with name and age attributes. We also define a constructor to initialize these attributes and a printDetails() method to display them. In the main() function, we create an object person1 of the Person class and call its printDetails() method.
What is an object in C++?
Stay tuned for the next part where we'll dive deeper into C++ objects and explore more practical examples! š