xxxxxxxxxx
// C++ code example demonstrating "C with classes"
#include <iostream>
class MyClass { // Class declaration
public: // Access specifier
int x; // Member variable
void printX() { // Member function
std::cout << "The value of x is: " << x << std::endl;
}
};
int main() {
MyClass obj; // Object creation
obj.x = 5; // Assigning a value to x
obj.printX(); // Calling the member function
return 0;
}
xxxxxxxxxx
// Define the struct to represent the class
typedef struct {
int x;
int y;
} MyClass;
// Function to create a new object of the class
MyClass* createMyClass(int x, int y) {
MyClass* obj = malloc(sizeof(MyClass));
obj->x = x;
obj->y = y;
return obj;
}
// Function to perform some operation on the object
void performOperation(MyClass* obj) {
// Access and modify object's properties
obj->x++;
obj->y--;
// Perform other operations
}
// Function to destroy the object and free memory
void destroyMyClass(MyClass* obj) {
free(obj);
}
// Example usage
int main() {
// Create a new object
MyClass* obj = createMyClass(10, 20);
// Perform operations on the object
performOperation(obj);
// Destroy the object
destroyMyClass(obj);
return 0;
}