🏢Classes
class ClassName { public: // Public members private: // Private members protected: // Protected members };
Last updated
class ClassName {
public:
// Public members
private:
// Private members
protected:
// Protected members
};Last updated
#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;
}