🧩 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.