Topic 47 of 83
Classes & Objects
Overview
A Class is a blueprint or template. An Object is an actual instance created from that blueprint. Classes define what an object will look like and how it will behave.
Syntax
cpp
// Class definition
class Player {
public:
int health = 100; // Attribute
void heal() { // Method
health += 10;
}
};
int main() {
// Creating an object (Instance)
Player p1;
// Using the object
p1.heal();
return 0;
}Common Pitfalls
- Forgetting the semicolon `;` at the end of the class closing brace `}`. This is a very common compiler error for beginners.
Interview Tips
- Understand the difference between a class (the architectural blueprint) and an object (the actual house built from the blueprint).
Real-World Example
Creating multiple independent objects from one class.
example
cpp
#include <iostream>
using namespace std;
class Dog {
public:
string name;
void bark() {
cout << name << " says Woof!" << endl;
}
};
int main() {
Dog dog1;
dog1.name = "Rex";
Dog dog2;
dog2.name = "Buddy";
dog1.bark(); // Rex says Woof!
dog2.bark(); // Buddy says Woof!
return 0;
}