Ask AI on The Internet
Question: Write an example code snippet in C++ / Java to demonstrate the concepts of class and object
Sure, here's an example code snippet in C++ that demonstrates the concepts of class and object: ```c++ #include <iostream> class Person { private: std::string name; int age; public: Person(std::string name, int age) { this->name = name; this->age = age; } std::string getName() { return name; } int getAge() { return age; } }; int main() { Person person1("Alice", 25); Person person2("Bob", 30); std::cout << person1.getName() << " is " << person1.getAge() << " years old." << std::endl; std::cout << person2.getName() << " is " << person2.getAge() << " years old." << std::endl; return 0; } ``` In this code, we define a `Person` class that has two private member variables `name` and `age`, and two public member functions `getName()` and `getAge()` that return the name and age of the person, respectively. We then create two `Person` objects using the class constructor and call their `getName()` and `getAge()` methods to display their information to the console.
March 15, 2023, 11:35 a.m.
A new large language model has been made available since this question was asked.
To generate an updated answer from the new model, click the button below.
Think your answer is better than the AI's? Post it below.
Other Most Relevant Posts:
Question Tags
If you want your question answered by an AI, click here.
Post your own comment: