Classes and Objects

Defining classes and creating objects

Interview Relevant: Core OOP concept

Classes and Objects

Classes are blueprints for creating objects with data and behavior.

Code Examples

Basic class definition and object creation.

cpp
1class Person {
2private:
3    string name;
4    int age;
5
6public:
7    // Constructor
8    Person(string n, int a) : name(n), age(a) {}
9
10    // Methods
11    void introduce() {
12        cout << "Hi, I'm " << name << ", " << age << " years old." << endl;
13    }
14
15    // Getter
16    string getName() const { return name; }
17
18    // Setter
19    void setAge(int a) {
20        if (a > 0) age = a;
21    }
22};
23
24// Create objects
25Person p1("Alice", 25);       // Stack allocation
26Person* p2 = new Person("Bob", 30);  // Heap allocation
27
28p1.introduce();
29p2->introduce();
30
31delete p2;

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In