Ask AI on The Internet
Ask Another Question Browse Other QuestionsQuestion: 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.
Think your answer is better than the AI's? Post it below.
Question Tags
If you want your question answered by an AI, click here.