Geek Slack

Learn C++
About Lesson


C++ Access Specifiers


C++ Access Specifiers

1. Public Access Specifier

Example of public access specifier:

#include <iostream>
#include <string>

// Class declaration
class Circle {
public:
    double radius;

    // Constructor
    Circle(double r) {
        radius = r;
    }

    // Member function to calculate area
    double calculateArea() {
        return 3.14159 * radius * radius;
    }
};

int main() {
    // Create object of class Circle
    Circle circle1(5.0);

    // Access public member variables and call member functions
    double area = circle1.calculateArea();
    std::cout << "Area of circle: " << area << std::endl;

    return 0;
}

2. Private Access Specifier

Example of private access specifier:

#include <iostream>
#include <string>

// Class declaration
class Rectangle {
private:
    double length;
    double width;

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

    // Member function to calculate area
    double calculateArea() {
        return length * width;
    }
};

int main() {
    // Create object of class Rectangle
    Rectangle rect(5.0, 3.0);

    // Access public member function to calculate area
    double area = rect.calculateArea();
    std::cout << "Area of rectangle: " << area << std::endl;

    // Error: Cannot access private member variables directly
    // std::cout << "Length: " << rect.length << ", Width: " << rect.width << std::endl;

    return 0;
}

3. Protected Access Specifier

Example of protected access specifier:

#include <iostream>
#include <string>

// Base class declaration
class Animal {
protected:
    std::string type;

public:
    // Constructor
    Animal(std::string t) : type(t) {}

    // Member function
    void displayType() {
        std::cout << "Type of animal: " << type << std::endl;
    }
};

// Derived class declaration
class Dog : public Animal {
public:
    // Constructor
    Dog(std::string t) : Animal(t) {}

    // Member function
    void bark() {
        std::cout << "Woof!" << std::endl;
    }
};

int main() {
    // Create object of class Dog
    Dog myDog("Canine");

    // Access protected member using derived class function
    myDog.displayType();

    // Error: Cannot access protected member directly
    // std::cout << "Type: " << myDog.type << std::endl;

    return 0;
}

Conclusion

Access specifiers in C++ control the visibility and accessibility of class members (variables and functions). This chapter covered public, private, and protected access specifiers, demonstrating how each affects member access within and outside the class. Understanding access specifiers allows you to design classes with appropriate data encapsulation and access control in C++ programs.

Join the conversation