🏢Classes
Classes are a fundamental concept in C++, providing a way to create user-defined types that encapsulate data and functions. They are a key feature of object-oriented programming in C++.
Basic Structure:
class ClassName { public: // Public members private: // Private members protected: // Protected members };
Access Specifiers:
public
: Accessible from outside the classprivate
: Accessible only within the class (default for classes)protected
: Accessible within the class and derived classes
Data Members: Variables declared within the class.
Member Functions: Functions declared within the class that operate on the class data.
Constructors: Special member functions for initializing objects.
Destructors: Special member functions for cleaning up when an object is destroyed.
This Pointer: Implicit pointer to the current object instance.
Static Members: Members shared by all instances of the class.
Const Members: Members that can't modify the object's state.
Friend Functions: Non-member functions given access to private members.
Example:
#include <iostream>
#include <string>
class Person {
private:
std::string name;
int age;
static int count; // Static member
public:
// Constructor
Person(const std::string& n, int a) : name(n), age(a) {
count++;
}
// Destructor
~Person() {
count--;
}
// Member function
void introduce() const {
std::cout << "Hi, I'm " << name << " and I'm " << age << " years old." << std::endl;
}
// Static member function
static int getCount() {
return count;
}
// Getter (const member function)
std::string getName() const {
return name;
}
// Setter
void setAge(int a) {
age = a;
}
// Friend function declaration
friend void displayAge(const Person& p);
};
// Static member initialization
int Person::count = 0;
// Friend function definition
void displayAge(const Person& p) {
std::cout << p.name << " is " << p.age << " years old." << std::endl;
}
int main() {
Person alice("Alice", 30);
Person bob("Bob", 25);
alice.introduce();
bob.introduce();
std::cout << "Total persons: " << Person::getCount() << std::endl;
displayAge(alice); // Friend function call
return 0;
}
Run it here.
Last updated