In C++, the beguilingly enigmatic class is a custom-made data type that allows programmers to encapsulate data and functions that bear upon that data.
This important concept of OOP represents a veritable game-changer, empowering the creation of objects, essentially viewed as class instances.
Table of Contents
Class Definition
A mysterious phenomenon known as a class is forged using a curious keyword called “class” in C++, that is pursued by a confounding name for the class, as well as the heart of the class, which includes data members and member functions.
An enclosure seeks the class name in fascinating curly braces.
To illustrate this peculiar concept, examine this perplexing code that establishes an introductory class called “Person”:
class Person { public: string name; int age; void print(){ cout<<"Name:"<<",Age:"<<age<<endl; } };
Data Members
Data members, variables that belong to a class and define an object’s state, can be classified as private, public, or protected. Their classification determines the accessibility of these members from outside the class. One can access public data members from anywhere.
In contrast, one can only access private data members from within the class in C++, and protected data members can be accessed from within the class and its subclasses.
Here’s an example to help you understand this concept better:
class Person { public: string name; int age; private: string ssn; };
In this example, name and age are public data members, while ssn is a private data member.
Member Functions
Member functions are essential functions that act on the data members of a class. These functions come in three flavors – private, public, or protected, and their level of accessibility from outside the class depends on which flavor they belong to.
Public member functions are universally accessible from anywhere. Private member functions can only access it from within the class, and protected member functions can be accessed from within the class and its subclasses.
To elaborate, let’s consider the following example.
class Person { public: string name; int age; void print(){ cout<<"Name:"<<name<<",Age:"<<age<<endl; } private string getSSN(){ return ssn; } };
In this instance, the print() member function can be utilized from anywhere in the codebase since it is public, while the get SSN () function can only be accessed privately within the class.
Constructors
Constructors are member functions that serve the exclusive purpose of initializing the data members of a class object during its creation. These functions bear the identical name as the class they belong to and do not yield any output. Constructors can be categorized into two types: default constructors and parameterized constructors.
Default constructors require no arguments, whereas parameterized constructors necessitate one or more parameters.
To acquire a more profound insight into constructors, let us delve into the following example, which will elaborate on this significant concept.
class Person { public: string name; int age; Person(){ name=""; age=0; } Person (string n, int a){ name=n; age=a; } };
In this example, Person() is a default constructor that initializes name and age to empty strings and zero, respectively. Person(string n, int a) is a parameterized constructor that takes a name and an age as parameters and initializes the corresponding data members.
Destructors
Destructors are special member functions that are called when an object is destroyed. They perform necessary cleanup tasks, such as releasing memory or closing files.
Destructors have the same name as the class preceded by a tilde (~) and no parameters or return type.
For example:
class Person { public: string name; int age; Person(){ name=""; age=0; } ~Person (){ cout<< Person"destructor has been called."<<endl; } };
In this example, the destructor of the “Person” class outputs a message indicating that it has been called.
Access Specifiers
Access specifiers are curious keywords that establish the visibility of data members and member functions. These keywords can have a private, public, or protected nature. Private data members and member functions are merely accessible from inside the class, while public ones can be accessed from anywhere.
As for protected ones, they lie somewhere in the middle, being accessible from within the class and its subclasses.
Inheritance
Inheritance is a crucial mechanism in object-oriented programming that allows a class to inherit the properties of another class. The base class or parent class is inherited, while the derived class or child class is the class that inherits from it.
The derived class can access the public and protected members of the base class, promoting code reuse and making it easier to create new classes.
For example:
c++ Copy code class Employee:public Person{ public: int salary; void printSalary(){ cout<<"Salary:"<<salary<<endl; } };
In this example, Employee is a derived class inherited from the Person base class. It adds a new data member called salary and a new member function called printSalary().
Polymorphism
Polymorphism is characteristic of objects that allows them to manifest diverse behaviors or functions based on the context in which they are used. This property facilitates code extensibility and modularity by enabling the creation of generic classes and methods that can operate on multiple object types.
One can achieve it through function overloading and virtual functions. Function overloading is the ability to define various functions with the same name but different parameters. Virtual functions are functions that are declared in the base class and described in the derived class. They allow a derived class to override the behavior of a base class function.
For example:
class Shape{ public: virtual void draw(){ cout<<"Drawing a shape."<<endl; } }; class Circle:public Shape{ public: void draw(){ cout<<"Drawing a circle."<<endl; } }; class Square:public Shape{ public: void draw(){ cout<<"Drawing a square."<<endl; } };
Encapsulation
Encapsulation is the intricately complex procedure of concealing the fine-grained implementation intricacies of a class from the external universe. This immensely aids in thwarting any inadvertent alterations to the data members and member functions.
Encapsulation accomplishment happens via access specifiers in the magnificent programming language, C++. Private data members and member functions are exclusively reachable from within the class, whereas public data members and member functions are reachable from all corners of the cosmos.
Example:
class BankAccount{ private: string accountNumber; double balance; punlic: void deposit(double amount){ balance+=amount; } void withdraw(double amount){ balance-=amount; } double getBalane(){ return balance; } };
In this example, the implementation details of the BankAccount class, such as the account number and `balance
Operator Overloading
The intricacy of operator overloading lies in the power to tweak the behavior of an operator as it interacts with objects of a class in C++. By doing so, programming enthusiasts can bask in the delight of more natural and intuitive syntax. C++ delivers a bunch of already defined operators, including but not limited to +, -, *, /, =, ==, !=, <=, >=, <, and >.
These operators can overload while operating on objects of a class. This implies that a solitary operator can execute distinct operations depending on the data type applied.
For example:
class Ponit{ public: int x,y; Point operator+(Point& other){ Point result; result.x=x+other.x; result.y=y+other.y; return result; } }; int main(){ Point p1={1,2} Point p2={3,4} Point p3=p1+p2; cout<<"Result:("<<p3.x<<","<<p3.y<<")"<<endl; return 0; }
In this example, there is an overload of the + operator to work with objects of the Point class. The operator+() function takes another Point object as a parameter, adds its x and y values to the corresponding values of the current object, and returns a new Point object that represents the result.
FAQS
What Are Access Specifiers In C++ Classes?
'Public,' 'Private,' and 'Protected' are access specifiers. - ‘public’: Users designated as members of the public interface can access them from outside the class. - ‘Private’: C++ classes restrict access to ‘Private’ members to only other class members. - `protected`: Similar to private, but the members declared as protected are also accessible to derived classes.
What Is A Destructor In C++?
When an object of a class exits its scope or is purposefully deleted, the destructor, a particular member function in the class, is automatically called. Before the object deallocates its memory, it uses it to release resources or carry out cleanup tasks. Destructors do not accept any arguments and do not have a return type.
In C++, What Distinguishes A Class From An Object?
In C++, a class is a blueprint or template that describes the structure and behavior of objects, whereas a thing is a newly created instance of that class in memory. The class defines what attributes and methods the objects will have, while the objects are the actual instances that hold specific data and can perform actions based on the class's blueprint.
Can A C++ Class Have Static Members?
A C++ class can have static members, including static variables and static member functions. Static members are not specific to instances but shared by all class objects. You access them using the class name, not through instances, and they can help store class-wide data or implement utility functions.
In C++, What Distinguishes A Class From A Struct?
The default access specifier for each member of a class and a struct in C++ is the main distinction between them. A struct's default members are ‘public,’ whereas a class's default members are ‘private.’ The choice between using a class or a struct often depends on the intended design and usage of the data structure, with a struct typically used for more straightforward data containers.
Can A C++ Class Inherit From Itself?
A class can indeed inherit from itself in C++; this is referred to as ‘recursive inheritance’ or ‘self-inheritance.’ However, due to the possibility of problems like infinite recursion, it is crucial to use this feature with caution. Due to the complexity and potential problems it can cause, it is not a common or advised practice. You should typically use inheritance to build a class hierarchy with a distinct base.
What is the necessity for classes in C++?
A class integrates data processing and data representation functions into one neat package. It defines the shape of an entity. Hence, the data and functions that make up a class are also its members.
What does a class in C++ indicate?
The C++ keyword in class indicates a custom data structure. A class is a group of C++ statements that define the state and behavior implementations. A class declaration creates a brand-new data type that you may use immediately.
Can you write C++ without classes?
Yes. The objective of writing object-oriented C++ code is possible. However, not all items are part of the same class. Hence, one can also develop functions that do not link to types.
Are classes a type of function?
Yes. Classes are actually 'special functions' that can be defined in the same way that functions can be. They generally use either a class expression or a declaration.
Can you send the same object to two different classes?
Yes, but only if one class inherits from the other. Otherwise, you cannot send the same object to two functions of separate classes. An example of an inherited class is the Object. You can also weakly type the thing after defining variables and functions.
Conclusion
A C++ class is a customized data type encapsulating data members and member functions. It furnishes a means to systematize and shape code and encourages reuse via inheritance. Access specifiers ascertain the perceptibility of data members and member functions. In contrast, polymorphism endows objects with the capability to assume diverse forms. Encapsulation assists in concealing the implementation minutiae of a class from external entities, and operator overloading permits more innate and discernible syntax. You can write proficient and sustainable C++ code by adeptly comprehending these principles.