Page Content

Tutorials

What Are Classes In C++, Access Specifiers With Code Example

Classes in C++

Classes are an essential language feature in C++ that let you create your own unique data types. They act as a guide or model outlining the characteristics (information) and actions (functions) that objects of that kind will have.

Data abstraction and encapsulation are the foundation of classes and object-oriented programming (OOP) in general. This indicates that a class distinguishes between its implementation (how it functions inside) and interface (what users can do with it). Without having to understand the intricate intricacies of the hidden implementation, users can interact with objects via the specified public interface.

A variable or instance of a class type that is made using the class blueprint is called an object. The data members of the class are replicated in each object.

Defining Classes

Member functions and data members (methods)

Class definitions include the class name, member names, and types.

Syntax for Class Definition: After the class keyword, class definitions normally include the class name. The class body is enclosed in curly brackets {} and ends with a semicolon ;.

class ClassName {
    // Access specifiers (public, private, protected)
    // Data members (variables)
    // Member functions (methods)
}; // Don't forget the semicolon!

Data Members

  • Description: The contents of objects of that class type are defined by data members, which are also referred to as characteristics, attributes, properties, or state. There will be distinct copies of these data components in every object derived from a class.
  • Declaration: Similar to regular variables, data members are declared inside the class body by first defining their type and then their name.
  • Example: Height, breadth, and length might all be data members of a Box class.

Member Functions (Methods)

  • Description: Member functions, which are often referred to as methods or capacities, specify the behaviours or activities that an object of the class is capable of performing. They are functions that are part of a class.
  • Interaction with Data: Member functions have immediate access to every member of the class for that object, including private members, and can and should be used to communicate with data members.
  • Calling: Only an instance (object) of the class may be used to call member functions.

Declaration and Definition

  • The class definition contains declarations for member function prototypes.
  • They may be implemented (defined) outside of the class declaration or inside of it, which makes them inline by default. The scope resolution operator:: is used to connect the function declaration to its class when it is defined outside. Defining functions outside of the class helps conceal implementation details and make header files more reusable and easier to maintain.

Example: GetVolume() might be a member function for the Box class.

Code Example: Let’s illustrate with a person class.

#include <iostream> // For input/output operations 
#include <string>   // For using std::string 
// Class definition 
class person {
    // Private data members: Accessible only by member functions of this class 
    // By default, members of a class are private if no access specifier is given 
    std::string name; // Data member to store the person's name 
    int age;          // Data member to store the person's age 
public:
    // Public member functions: Define the interface for interacting with person objects 
    void getdata(void); // Member function to get data for a person 
    void display(void); // Member function to display person's data 
};
// Member function definitions outside the class using the scope resolution operator (::) 
void person::getdata(void) {
    std::cout << "Enter name: "; // Output to standard output 
    std::cin >> name;           // Read input from standard input 
    std::cout << "Enter age: ";
    std::cin >> age;
}
void person::display(void) {
    std::cout << "\nName: " << name; // Accessing private data members directly 
    std::cout << "\nAge: " << age << std::endl;
}
int main() {
    person p; // Create an object (an instance) of the 'person' class 
    p.getdata();  // Call the 'getdata' member function for object 'p' 
    p.display();  // Call the 'display' member function for object 'p' 
    // Another example with a simple class demonstrating public data members
    // This style is less common for full classes due to lack of encapsulation.
    class point {
    public:
        int x, y; // Public data members 
    };
    point myPoint; // Create an object of the 'point' class
    myPoint.x = 10; // Directly access public data member
    myPoint.y = 20;
    std::cout << "\nMy Point: x=" << myPoint.x << ", y=" << myPoint.y << std::endl;
    return 0;
}

Output

Enter name: Govindhtech
Enter age: 2
Name: Govindhtech
Age: 2
My Point: x=10, y=20

Access Specifiers (Public, Private, Protected)

Protected, Private, and Public Access Specifiers C++ access specifiers control member visibility and encapsulation. Which program components can access the members is determined by these specifiers.

  • public: All areas of the program can access members defined after a public specifier. The class’s interface is usually defined by these members.
  • private: Only members functions and friends of the class in which they are declared can access members defined after a private specifier. Usually, data members and utility functions use this to conceal implementation specifics.
  • protected: Both member functions and friends of the class in which they are declared, as well as member functions and friends of classes derived from this class, can access members that have been defined as protected. This is used when a base class wishes to make some aspects of its implementation available to its derived classes while maintaining their inaccessibility to standard user code.
  • Default Access: Members are by default private when the class keyword is used. Members are by default made public if struct is used.

Classes vs. Structs

C++ class and struct keywords can define classes with member functions and data members, making them functionally equivalent. Their default access level is the sole technological distinction. Whereas class is used when there are private members and a focus on building a correct type with invariants and specified behaviour, struct is typically used for classes that primarily group data (Plain Old Data or POD types).

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index