Notifications
Clear all
Topic starter 01/08/2025 11:40 pm
C++ classes are a cornerstone of its object-oriented programming paradigm, allowing you to bundle data and behaviors into neat, reusable structures.
🏗️ Defining a Class
You start with the class
keyword:
class Dog {
public:
string name;
string breed;
void speak() {
cout << name << " says woof!" << endl;
}
};
public
means accessible outside the class- You can also use
private
andprotected
to control access
🐾 Creating and Using an Object
Dog myDog;
myDog.name = "Fido";
myDog.breed = "Labrador";
myDog.speak(); // Fido says woof!
🛠️ Constructors and Destructors
Used to initialize and clean up objects:
class Dog {
public:
Dog(string n, string b) { name = n; breed = b; } // Constructor
~Dog() {} // Destructor
void speak() {
cout << name << " says woof!" << endl;
}
private:
string name;
string breed;
};
Dog myDog("Fido", "Labrador");
🧬 Inheritance
C++ supports single and multiple inheritance:
class Puppy : public Dog {
public:
void speak() {
cout << "Squeak!" << endl;
}
};
⚙️ Accessors and Encapsulation
To safely access private variables:
class Dog {
private:
string name;
public:
void setName(string n) { name = n; }
string getName() { return name; }
};
💡 Other Key Concepts
- Static members: Shared across all instances
- Friend functions: Access private data from outside
- Operator overloading: Customize behavior of
+
,==
, etc.
C++ classes give you fine-grained control and performance—all while promoting clean, scalable code.