Data Members of Class

Member Functions

Type Purpose Example
Accessor ("getter") Reads a data member's value without modifying it double getBalance() const { return balance; }
Mutator ("setter") Modifies a data member's value in a controlled way void deposit(double amt) { balance += amt; }
Utility/helper Performs a computation using the object's data double area() { return length * width; }
Constructor/Destructor Special member functions for initialization/cleanup see the Rectangle example below

Access Specifiers (Data Members & Member Functions visibility)

Specifier Accessible from
private Only within the same class (default for class)
protected Same class + any derived class, not from outside
public Anywhere the object is visible

Note: struct defaults to public access; class defaults to private — a classic MCQ trap.

Basic worked example — Data Members, Member Functions, Constructor, Destructor together

#include <iostream>
using namespace std;

class Rectangle
{
private:
    double length, width;   // data members -- hidden from outside access

public:
    Rectangle(double l, double w) : length(l), width(w)   // constructor
    {
        cout << "Rectangle created.\n";
    }

    double area() { return length * width; }        // member function
    double perimeter() { return 2 * (length + width); }

    ~Rectangle()   // destructor
    {
        cout << "Rectangle destroyed.\n";
    }
};

int main()
{
    Rectangle r(5, 3);
    cout << "Area: " << r.area() << endl;
    cout << "Perimeter: " << r.perimeter() << endl;
    return 0;   // destructor runs automatically here
}

Output:

Rectangle created.
Area: 15
Perimeter: 16
Rectangle destroyed.