๐งฉ Part 1: Access Specifiers in C++
Access specifiers determine the visibility and accessibility of class members (variables and functions) to other parts of the program.
๐ถ 1. Public
- Members are accessible from anywhere (inside or outside the class).
- Used for interface functions that can be used by other classes or the main program.
โ Example:
class Student {
public:
int rollNo;
void display() {
cout << "Roll No: " << rollNo << endl;
}
};
int main() {
Student s;
s.rollNo = 101; // โ
Allowed
s.display(); // โ
Allowed
}
๐ถ 2. Private
- Members are only accessible within the class.
- Cannot be accessed directly from outside the class.
- Ensures data hiding and security.
โ Example:
class Student {
private:
int rollNo;
public:
void setRollNo(int r) {
rollNo = r;
}
void display() {
cout << "Roll No: " << rollNo << endl;
}
};
int main() {
Student s;
// s.rollNo = 101; โ Not allowed (private)
s.setRollNo(101); // โ
Allowed via public function
s.display(); // โ
}
๐ถ 3. Protected
- Similar to private, but accessible in derived classes (inheritance).
- Commonly used in inheritance scenarios.
โ Example:
class Person {
protected:
string name;
public:
void setName(string n) {
name = n;
}
};
class Student : public Person {
public:
void display() {
cout << "Name: " << name << endl; // โ
Accessible in derived class
}
};
int main() {
Student s;
s.setName("Alice");
s.display();
}
๐ท Summary Table: Access Specifiers
| Access Level | Inside Class | Outside Class | In Derived Class |
|---|---|---|---|
public | โ Yes | โ Yes | โ Yes |
private | โ Yes | โ No | โ No |
protected | โ Yes | โ No | โ Yes |
๐งฉ Part 2: Array of Objects
An array of objects is a collection of multiple objects of the same class, stored in an array. It allows you to manage multiple instances efficiently.
โ Syntax:
cppCopyEditClassName objectArray[array_size];
๐ถ Example:
#include <iostream>
using namespace std;
class Student {
public:
int rollNo;
string name;
void getData() {
cout << "Enter roll number: ";
cin >> rollNo;
cout << "Enter name: ";
cin >> name;
}
void display() {
cout << "Roll No: " << rollNo << ", Name: " << name << endl;
}
};
int main() {
Student s[3]; // Array of 3 Student objects
cout << "--- Enter Student Details ---" << endl;
for (int i = 0; i < 3; i++) {
s[i].getData();
}
cout << "\n--- Displaying Student Details ---" << endl;
for (int i = 0; i < 3; i++) {
s[i].display();
}
return 0;
}
๐ท Key Points:
- Each element in the array (
s[0],s[1],s[2]) is a separate object. - You can call member functions for each object using: cppCopyEdit
s[i].functionName(); - Useful when dealing with multiple records like students, employees, books, etc.
๐ Final Summary
โ Access Specifiers:
- public: accessible everywhere
- private: only inside the class
- protected: class + derived classes
โ Array of Objects:
- A collection of multiple class objects.
- Use loops to handle object input/output efficiently.
- Helps in building programs that manage lists of entities.
