0% found this document useful (0 votes)
12 views6 pages

C++ Class Access Specifiers Explained

The document contains 5 questions that demonstrate the use of access specifiers (private, protected, public) in C++ classes. Question 1 creates a Car class with private, protected, and public data members and shows how they can be accessed. Question 2 creates a Rectangle class with private length and width and public methods to calculate area and perimeter. Question 3 creates a base Vehicle class with protected members and derived Car and Bike classes. Question 4 creates an InventoryManager class with private data structure to manage inventory items. Question 5 creates a Student class and functions to manage student records like adding, displaying, calculating average marks.

Uploaded by

domeslack
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views6 pages

C++ Class Access Specifiers Explained

The document contains 5 questions that demonstrate the use of access specifiers (private, protected, public) in C++ classes. Question 1 creates a Car class with private, protected, and public data members and shows how they can be accessed. Question 2 creates a Rectangle class with private length and width and public methods to calculate area and perimeter. Question 3 creates a base Vehicle class with protected members and derived Car and Bike classes. Question 4 creates an InventoryManager class with private data structure to manage inventory items. Question 5 creates a Student class and functions to manage student records like adding, displaying, calculating average marks.

Uploaded by

domeslack
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Q1. Consider a class named `Car` with private, protected, and public members.

Create an
object of the class and demonstrate how each type of access specifier works in accessing the
members.
#include <iostream>

class Car {
private:
int privateSpeed; // Private member
protected:
int protectedSpeed; // Protected member
public:
int publicSpeed; // Public member

// Constructor to initialize speeds


Car(int privateSpeed, int protectedSpeed, int publicSpeed) {
this->privateSpeed = privateSpeed;
this->protectedSpeed = protectedSpeed;
this->publicSpeed = publicSpeed;
}

// Method to display speeds


void displaySpeeds() {
std::cout << "Private speed: " << privateSpeed << std::endl;
std::cout << "Protected speed: " << protectedSpeed << std::endl;
std::cout << "Public speed: " << publicSpeed << std::endl;
}
};

int main() {
Car myCar(100, 120, 140); // Creating an object of the Car class

// Accessing public member


std::cout << "Accessing public speed: " << [Link] <<
std::endl;

[Link](); // Demonstrating accessing all speeds through


a member function

return 0;
}
Q2. Create a class `Rectangle` with private attributes length and width. Implement methods
inside the class to calculate the area and perimeter of the rectangle. Use appropriate access
specifiers.
#include <iostream>

class Rectangle {
private:
double length;
double width;

public:
// Constructor
Rectangle(double l, double w) : length(l), width(w) {}

// Method to calculate area


double calculateArea() {
return length * width;
}

// Method to calculate perimeter


double calculatePerimeter() {
return 2 * (length + width);
}
};

int main() {
// Create a rectangle object with length 5 and width 3
Rectangle rect(5, 3);

// Calculate and display area


std::cout << "Area: " << [Link]() << std::endl;

// Calculate and display perimeter


std::cout << "Perimeter: " << [Link]() << std::endl;

return 0;
}
Q3. Design a base class Vehicle with protected data members like speed and colour. Derive
classes Car and Bike with additional features. Implement methods to display vehicle details.
#include <iostream>
#include <string>

class Vehicle {
protected:
int speed;
std::string color;

public:
Vehicle(int _speed, std::string _color) : speed(_speed),
color(_color) {}

void displayDetails() {
std::cout << "Vehicle Details:" << std::endl;
std::cout << "Speed: " << speed << " km/h" << std::endl;
std::cout << "Color: " << color << std::endl;
}
};

class Car : public Vehicle {


private:
std::string brand;

public:
Car(int _speed, std::string _color, std::string _brand)
: Vehicle(_speed, _color), brand(_brand) {}

void displayDetails() {
Vehicle::displayDetails();
std::cout << "Brand: " << brand << std::endl;
}
};

class Bike : public Vehicle {


private:
std::string type;

public:
Bike(int _speed, std::string _color, std::string _type)
: Vehicle(_speed, _color), type(_type) {}

void displayDetails() {
Vehicle::displayDetails();
std::cout << "Type: " << type << std::endl;
}
};

int main() {
Car myCar(120, "Red", "Toyota");
Bike myBike(80, "Blue", "Mountain");

[Link]();
std::cout << std::endl;
[Link]();

return 0;
}

Q4. Design a class for managing inventory items with private data members. Use access
specifiers to control access and implement methods for item addition and display.
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class InventoryManager {
private:
struct Item {
string name;
int quantity;
};

vector<Item> inventory;

public:
void addItem(const string& itemName, int quantity) {
Item newItem;
[Link] = itemName;
[Link] = quantity;
inventory.push_back(newItem);
}

void displayInventory() {
cout << "Inventory:\n";
for (const auto& item : inventory) {
cout << [Link] << " - Quantity: " << [Link] <<
endl;
}
}
};

int main() {
InventoryManager manager;

// Adding items to inventory


[Link]("Item1", 10);
[Link]("Item2", 5);

// Displaying inventory
[Link]();

return 0;
}
Q5 .Design a simple program to manage student information using methods in C++. The
program should be able to add new students, display student details, and calculate the
average marks of all students. Define some functions outside class using the scope
resolution operator.
#include <iostream>
#include <vector>

using namespace std;

// Class to represent a student


class Student {
public:
string name;
int marks;
};

vector<Student> students; // Vector to store student objects

// Function to add a new student


void addStudent() {
Student newStudent;
cout << "Enter student name: ";
cin >> [Link];
cout << "Enter marks: ";
cin >> [Link];
students.push_back(newStudent);
}

// Function to display all students


void displayStudents() {
cout << "Student Information:" << endl;
for (const auto &student : students) {
cout << "Name: " << [Link] << ", Marks: " << [Link]
<< endl;
}
}

// Function to calculate the average marks of all students


double calculateAverageMarks() {
if ([Link]()) {
return 0.0;
}

int totalMarks = 0;
for (const auto &student : students) {
totalMarks += [Link];
}

return static_cast<double>(totalMarks) / [Link]();


}

int main() {
int choice;

do {
cout << "\n1. Add new student\n2. Display student details\n3.
Calculate average marks\n4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
addStudent();
break;
case 2:
displayStudents();
break;
case 3:
cout << "Average Marks: " << calculateAverageMarks() <<
endl;
break;
case 4:
cout << "Exiting program.\n";
break;
default:
cout << "Invalid choice. Please try again.\n";
break;
}
} while (choice != 4);

return 0;
}

Common questions

Powered by AI

While method overloading is not directly applied in the provided designs, each design follows principles that could benefit from method overloading. In a geometrical calculation context, like in the `Rectangle` class, method overloading could allow multiple versions of `calculateArea()` or `calculatePerimeter()`, accepting different parameters or implementing variations depending on the context (such as different units or precision levels). Similarly, for vehicle details, method overloading could enhance `displayDetails()` in `Vehicle`, `Car`, and `Bike` to accept different verbosity levels or output formats. This supports flexible and adaptable class functionality, allowing methods to cater to varying operational needs without altering core behavior or interface .

The `InventoryManager` effectively demonstrates encapsulation by containing all item management within the class itself. Items are encapsulated as private data, accessed and modified only through public class methods, thus promoting data integrity and hiding implementation details. In contrast, the student management program uses a global `students` vector that can be accessed and modified by external functions like `addStudent()` and `displayStudents()`. This reduces encapsulation, as the global state is exposed, potentially leading to uncontrolled modifications and complicating maintenance. The `InventoryManager` demonstrates a more robust approach to data management by limiting direct access and providing controlled interaction, enhancing maintainability and reducing the risk of errors due to unanticipated external changes .

Inheritance in this context allows the `Car` and `Bike` classes to extend the functionality of the `Vehicle` class. The `Vehicle` class provides a foundation with `speed` and `color` as protected members, making them accessible to derived classes. Consequently, `Car` and `Bike` can implement additional specific features like `brand` and `type` while still accessing and utilizing the base `Vehicle` properties. The derived classes also implement their versions of the `displayDetails()` method, which extend the base class's functionality to include specific attributes of a `Car` or `Bike` .

The `InventoryManager` class manages inventory items by encapsulating them within a private `Item` structure. The `inventory` vector stores `Item` objects, which contain `name` and `quantity`. Public methods `addItem()` and `displayInventory()` are provided to add new items, specifying name and quantity, and to display current inventory details respectively. This approach effectively manages data encapsulation by restricting direct access to inventory items and adhering to controlled interactions via class methods .

The use of private data members in the `Rectangle` class, namely `length` and `width`, encapsulates these properties, preventing direct modification from code outside the class. This ensures that control is maintained over the data integrity of the `Rectangle` objects. The class methods `calculateArea()` and `calculatePerimeter()` operate directly on these private members, providing controlled access and manipulation of `length` and `width`. This design enforces encapsulation, a key principle in object-oriented programming, by using class methods to interact with the object’s data .

In C++, access specifiers control the accessibility of class members, which include `private`, `protected`, and `public`. In the `Car` class example, `privateSpeed` is private and can only be accessed within the class itself, meaning it cannot be directly accessed outside the class. `protectedSpeed` is protected, allowing it to be accessed in derived classes or within the same package but not outside. Meanwhile, `publicSpeed` is public and can be accessed from anywhere an object of the class exists. This is demonstrated by the ability to access `publicSpeed` directly in the `main` function, while `privateSpeed` and `protectedSpeed` are accessed through a public function `displaySpeeds()` .

Constructors in the `Car`, `Rectangle`, and `Vehicle` classes are designed to initialize object attributes upon creation. In the `Car` class, the constructor initializes `privateSpeed`, `protectedSpeed`, and `publicSpeed`, setting essential initial states. The `Rectangle` constructor takes `length` and `width` as parameters to initialize the dimensions of the rectangle, ensuring the object is properly set up before use. In the `Vehicle` class, the constructor sets up the `speed` and `color`, laying the groundwork for the likes of `Car` and `Bike` to inherit and extend these properties. Constructors ensure object integrity and enforce initial conditions required for the objects to operate correctly .

The advantages of using a struct within a class, as shown in the `InventoryManager`, include simplified syntax for encapsulating related attributes and lightweight object creation. It aids in logically grouping data, enhancing readability and organization without needing full class functionality. However, the use of structs also comes with limitations. Structs inherently lack methods, restricting the encapsulation to strictly data and relying on external functions or class methods for manipulation. This simplicity can lead to less rigid control over data operations compared to a full class design, potentially compromising encapsulation if not adequately managed .

In the student information program, global variables like `students` have a program-wide lifetime, persisting throughout the program's execution. This allows any function to access the student data without restrictions, creating potential risks of accidental modification, though it offers ease of access for various functionalities across the program. Functions defined outside of any class operate within the global scope, executing with each function call through the program loop maintained in `main()`. This structure intensifies dependency on the global state, potentially leading to difficulties in debugging and scaling due to tight coupling and reduced encapsulation, countering object-oriented paradigms which favor restricted scope and encapsulated state for robust and maintainable software solutions .

The student information management program defines several functions outside of any class using the C++ scope resolution operator, namely `addStudent()`, `displayStudents()`, and `calculateAverageMarks()`. This structural choice decouples functionality from class definitions, promoting modular program design. It allows these functions to directly manipulate the global `students` vector. While this enhances flexibility and simplicity in some scenarios, it reduces encapsulation as global state manipulation occurs outside object-oriented constructs, possibly leading to harder-to-maintain code due to the decreased encapsulation and increased global state reliance .

You might also like