Class and Object in C++ are the basic and common structures in C++ or OOPs.

Class in C++

Click this link for details

Object in C++

Click this link for details

Class Member (Data Member/Member Data & Member Function) 
  • Member of a class in C++ usually consists of data variables (called Data Members) and functions (called Member Functions).
  • It is the actual interface that initiates an action for an object belonging to a class.
  • It is normally used to read, manipulate, or display the data member.
  • Data Member :
    • The data member of a class is a variable that must be declared within the body of the class either publically/privately/protected.
  • Member Function :
    • A member function is a function that is always declared inside a class and is responsible for performing certain operations required by the class.
    • The member functions of a class can be defined in two ways: –  (i) Function is defined inside the class (ii) Function is defined outside the class with the help of scope resolution operator(::).However, irrespective of the location of their definition, the member function must have identical code and perform the same operation. The compiler treats these two definitions differently.
Nesting of Member Functions 
  • When a member function calls any another member function of the same class directly, inside it, irrespective of its privilege, without using the dot operator. This is called as nesting of member functions.
  • In other words, A member function can be called by using its name inside another member function of the same class, known as the nesting of member functions.
  • In a nested member function, a function that includes another function inside it is called an outer function and the function included inside an outer function is called an inner function. Here, the outer function is called with the help of the object of that class first and then the inner function is called directly with the help of the outer function.
Inline Function
  • Definition 
    • In C++, an inline function is a function for which the compiler attempts to insert the complete body of the function wherever it is called, instead of performing a regular function call. This can improve performance by avoiding the overhead of a function call, but it may increase the size of the binary if used excessively.
    • Inline functions are a powerful tool for optimizing small functions. 
  • Features
    • The inline function is created using the inline keyword before the function definition.
    • The inline function takes the format as a normal function but when it is compiled it is compiled as inline code. The function is placed separately as an inline function, thus adding readability to the source program. When the program is compiled, the code present in the function body is replaced in the place of the function call. 
    • Inline functions must be defined in the same file where they are called because the compiler needs the full definition to inline them.
    • The inline function instructs the compiler to insert the complete body of the function wherever that function is used in the code.
    • The compiler may ignore the inline request if inlining the function would not be beneficial (i.e. if the function is too complex).
    • The functions are defined as inline when the function is small and is called many times.
    • By doing inline, the function gets executed as inline, which removes the control transfer to that function’s body.
    • Generally, a member function is made inline by adding a keyword inline in front of its return type in its declaration.
    • An inline function is written in one line when they are invoked. These functions are very short and contain one or two statements.
  • Syntax
inline return_type function_name(parameters)
{
    // Function body
}
  • Reason to Choose Inline Function
    • Normally, a member function call transfers the control from the calling program to the function, and after the execution of the program returns the control to the calling program after the function call. These concepts of function save program space and memory space and are used because the function is stored only in one place and is only executed when it is called. This execution may be time-consuming since the registers and other processes must be saved before the function gets called. The extra time needed and the process of saving are valid for larger functions. If the function is short, the programmer may wish to place the code of the function in the calling program for it to be executed. This type of function is best handled by the inline function.
  • Advantages
    • Inline functions can execute much faster than normal functions because inline functions might decrease the number of cache misses thus Inline functions usually improve CPU-bound applications to run faster.
    • This function reduced the function call overhead i.e., no stack frame is set or teardown is required since the complete function is replaced in the inline function.
    • Inline Function is particularly useful for small, frequently called functions (where performance is high) like getters, setters, or simple mathematical operations.
    • The inline function keeps the code cleaner and modular while avoiding the function call overhead.
    • It also saves the overhead of push/pop variables on the stack when the function is called. 
    • It also saves the overhead of a return call from a function.
  • Disadvantages
    • If a function is inlined at multiple locations, the binary size/code increases, potentially leading to code bloat.
    • Functions with loops, recursion, or static variables are unlikely to be inlined. The compiler may not inline this function because recursion requires a real function call.
    • If the inline function is too large, then the program grows larger (become slower). So, in general, only short functions are declared as inline functions.
    • Reduced debugging ease i.e., debuggers may find it harder to trace inline functions because there is no actual function call at runtime.
    • The compiler may ignore the inline directive if it seems the function is too complex to inline.
Friend Function  
  • In C++, a friend function is a special function that grants special access to the private and protected members of a class, even though it is not a member of the class itself.
  • Friend functions are declared using the friend keyword inside the class whose private members they need to access.
  • Friendship does not extend to derived classes.
  • A typical non-member function (a normal function outside the class)cannot have an access right to the private data of a class but C++ provides a special feature called the friend function (a non-member function, i.e., not a member of any class.) which is used to access the private members of a class.
  • Syntax :
class ClassName
{
    friend return_type friend_function_name(parameters);
};
  • A friend function can also access private members of multiple classes if declared as a friend in each of them.
  • Friend functions are often used for operator overloading, especially for binary operators that need access to private members of both operands.
  • Friend function causes Security Implications hence the use of friend functions sparingly as they break encapsulation principles.
  • When to Use Friend Functions
    • When a non-member function requires access to private/protected members of a class.
    • For operator overloading that involves private members of a class.
    • When two or more classes need to share private data for certain operations.
  • Some special properties of the friend function are : –
    • A friend function is not in the scope of the class to which it has been declared as a friend.
    • A friend function cannot be called using the object of that class. It is called simply as a normal function i.e., unlike member functions, friend functions are called like regular functions.
    • It can be invoked like a normal function without the use of any object.
    • Unlike member functions of a class, it can not access the class members directly. However, it can use the object and dot operator with each member name to access both private and public members of a class.
    • Friend function can be declared either in the public or the private part of a class without affecting its meaning.
    • Usually, it has objects as arguments.
Friend Classes 
  • friend class is a class that can access all the private and protected members of another class in which it is declared as a friend.
  • Like a friend function, a class can also be a friend of another class.
  • To access the private and protected members of a class in the friend class we must pass on an object of a class to the member functions of the friend class.
  • This is needed when we want to allow a particular class to access the private and protected members of a class.
  • A significant use of a friend class is for a part of a data structure, represented by a class, to provide access to the main class representing that data structure.
 Scope Resolution Operator(::) 
  • The scope resolution operator (::) in C++ is used to access or define members of a class, namespace, or global variables that might be overshadowed by local variables. 
  • Scope resolution operators are specific operators that work on names rather than values.
  • The main use of scope resolution operators is in various important activities in C++. These are –
    • If the global variable name is the same as the local variable name, the scope resolution operator will be used to call the global variable.
    • This operator is used to get hidden names of variables due to variable scopes so that we can still use them.
    • It is also used to define a function outside the class.
    • It is used to access the static variables of a class.
    • It is used to referring a class inside another class.
    • It helps resolve ambiguities in the scope of identifiers in the case of multiple Inheritance.
    • In Namespace declaration.
    • It can be used as both unary and binary operation.
Visibility/Accessibility/Access Specifiers of class members 
  • Access specifiers are a fundamental concept in object-oriented programming (OOP) and play a crucial role in designing secure and maintainable code.
  • Access specifiers in C++ are the collection of keywords used to define the accessibility (or visibility) of class members (attributes/data members and methods). They determine how and where the members of a class can be accessed from other parts of a program.
  • Access specifiers are necessary for data encapsulation, is to prevent accidental modification of information of a class also data can be protected from external tempering by users and access to specific methods can also be controlled.
  • To access the members of a class in a controlled way (so that a process is managed well), a set of rules is imposed in which a class is to be manipulated and data and functions of the class can be accessed. The set of rules is known as accessibility rules. These accessibility rules are achieved by using these three keywords – private, public, and protected. These keywords are also called access-control specifiers.
  • Importance :
    • Access specifiers support encapsulation that protects sensitive data and enforces data hiding.
    • Access specifiers provide flexibility by controlling how class members are accessed by other parts of the program.
    • Access specifiers support Inheritance control in which protected members enable derived classes to access base class members while keeping them hidden from outside the class.
  • The Access Specifiers table is –
    Access specifiers Accessible by the Object of
    Within/Same Class  Derived Class Outside Class
    public Yes Yes Yes
    private Yes No No
    protected Yes Yes No
  • Types of Access Specifiers:
    • There are three types of Access Specifiers in C++ – (1) Public (2) Private (3) Protected
    • They are collectively called visibility labels and are used to control the access to members (data members and member functions) of a class. 
    • Access specifiers can be mixed within a single class.
    • A class can use all three visibility/accessibility labels one or more times.
    • Public :
      • The public members of a class can be accessed directly by objects of the same or another class (having no security) without the member function of the class.
      • Members declared as public (using the keyword public :)can be accessed from anywhere in the program.
      • These members are directly accessible by other classes and functions.
    • Private :
      • In C++, members of a class (member data & member function), without specifying any access specifier are considered private by default. In other words, this is the default access level for class members if no specifier is explicitly mentioned.
      • A complete/totally private class (both member data & member function), is hidden from the external world and usually does not serve any useful purpose/not behavioral.
      • Normally, private members of a class are not accessible directly by outside class but we can access the private members of a class from outside a class using friends, pointers to members, etc. from outside the class.
      • The private members of the class can only accessed by the public member function of the same class.
      • Members declared as private (using the keyword private :) can only be accessed within the class itself.
    • Protected :
      • Members declared as protected (using the keyword protected :)can only be accessed:
        • Within the class itself.
        • By derived (child) classes.
      • They are not accessible directly by objects of the outside class.
      • The protected members of a class are similar to private except, that the object of the derived class can access protected members of the base class directly without the member function of the base class.
      • The protected access specifier is mainly associated with Inheritance.
Function Overloading  
  • Function overloading is one of the most powerful features in C++ that allows multiple functions with the same name to be defined but with different parameters. The compiler differentiates between these functions by their parameter list (also called the function signature).
  • Function overloading refers to using the same thing for different purposes.
  • It is a very good example of polymorphism (compile-time polymorphism/static binding).
  • Function Overloading not only provides support for compile time polymorphism, it also adds flexibility and convenience to the program.
  • C++ permits the use of different functions with the same name, having essentially different argument lists. The difference can be in terms of the number of arguments or datatype of arguments or both or the order of parameters. It is only through these differences, that the compiler knows which function to call in at any given situation.
  • The compiler knows when to call which function (by deciding/determining the argument list) if there is more than one function of the same name. The function call determines which function definition will be executed.
  • The biggest advantage of overloading is that it helps to perform the same operations on different datatypes without having the need to use separate names for each version.
  • Overloading of functions with different return types is not allowed.
  • The use of overloading may not have reduced the code complexity /size but has made it easier to understand and avoided the necessity of remembering different names for each version function which performs identically the same task.
  • When an overloaded function is called, C++ goes through the following process to determine which version of the function will be called, i.e. first, C++ tries to find an exact match in which the actual argument exactly matches the parameter type of one of the overloaded functions.
  • The working mechanism of function overloading can be explained using three outcomes – 
    • If a match is found, the call is resolved to a particular overloaded function.
    •  If no match is found, the arguments can not be matched to any overloaded function.
    • If an ambiguous match is found, the arguments match more than one overloaded
      function.
  • Ambiguous matches is a situation in which the compiler is unable to choose between two (or more) overloaded functions. When this happens, the situation is said to be ambiguous. Ambiguous statements are errors, and programs containing ambiguity will not compile. Thus, ambiguous matches are considered a compile-time error.
  • An ambiguous match needs to be disambiguated before the program will compile. There are two ways to resolve ambiguous matches:
    • The best way is simply to define a new overloaded function that takes parameters of exactly the type we are trying to call the function with. Then we will be able to find an exact match for the function call.
    • Alternatively, explicitly cast the ambiguous parameter(s) to the type of function we want to call.
Static Keyword (Static Data Member & Static Member Function) 
  • Static Keyword :
    • Static keyword is used to manage memory and control the scope of variables and functions in  C++.
    • Static is a keyword or a storage class specifier/qualifier that provides information about the locality and visibility of variables in a class.
    • The members of a class can be made static using this keyword before the name of the data member and function member of a class.
  • Static Class :
    • A class containing a static member, either a data member or member function, is called a Static class.
    • A class may contain both static as well as non-static data members, with or without static member function.
    • A class may contain at least one/more static data members or member functions.
  • Static Variables/Data Members :
    • Static Variables:
      • When static data or variables are declared inside the normal function (not in the member function of a class), it is called Static Local Variables and when outside the normal function it is called Static Global Variables.
      • A static local variable inside a function retains its value across multiple (object) calls to the function.
      • A static global variable has internal linkage, i.e., it has limited access to the file in which it is declared. It cannot be accessed from other files, unlike a normal global variable.
      • It is initialized only once, and its value persists between function calls.
    • Static Data Members:
      • When static data or variables are declared inside the class, it is called Static Data Members.
      • A static data member of a class is shared among all objects of that class.
      • Memory is allocated only once for static data members, regardless of the number of objects created.
      • Static data members are accessible by all objects of that class equally and each object uses the same static data member.
      • The static data member must initialize with zero/certain values when the first object of its class is created. They are normally initialized outside the class.
      • Static data member is a variable and is part of a class, not the part of an object of that class, it is called a class variable.
      • There is exactly one copy of static data member that exists as a whole instead of one copy per object, as for ordinary non-static data members.
  • Static Functions/Member Functions :
    • Static Functions :
      • When a normal function is declared static, it is called a Static Function.
      • A static function can only be called within the file where it is defined.
    • Static Member Functions :
      • When a member function is declared static, it is called a Static Member Function.
      • A static member function can be called without an object of the class. A static member function is called using the class name directly instead of its object. 
      • It can only access other static members (both data and functions) of the class.
      • The static member function can only access the static member(data or function) declared in the same class.
Passing Objects (as Arguments) to Function, Returning Objects & Objects Assignment in a Class  
  • When we pass objects as parameters to a function, normally inside the main method like any other data type of a class is known as passing objects as arguments.
  • This can be done by a pass-by-value and a pass-by-reference. In pass-by-value, a copy of the object is passed to the function and any modifications made to the object inside the function are not reflected in the object used to call the function. While, in pass-by-reference, an address of the object is passed to the function and any changes made to the object inside the function are reflected in the actual object.
  • we can also return objects from the function like any other data type.

Loading

Categories: C++

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.