Blog

  • Static Members of a C++ Class

    Static Members of a Class

    We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member.

    A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. We can’t put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to.

    Example

    Let us try the following example to understand the concept of static data members −

    #include <iostream>usingnamespace std;classBox{public:staticint objectCount;// Constructor definitionBox(double l =2.0,double b =2.0,double h =2.0){
             cout <<"Constructor called."<< endl;
             length = l;
             breadth = b;
             height = h;// Increase every time object is created
             objectCount++;}doubleVolume(){return length * breadth * height;}private:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a box};// Initialize static member of class Boxint Box::objectCount =0;intmain(void){
       Box Box1(3.3,1.2,1.5);// Declare box1
       Box Box2(8.5,6.0,2.0);// Declare box2// Print total number of objects.
       cout <<"Total objects: "<< Box::objectCount << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Constructor called.
    Constructor called.
    Total objects: 2
    

    Static Function Members

    By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.

    A static member function can only access static data member, other static member functions and any other functions from outside the class.

    Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not.

    Example

    Let us try the following example to understand the concept of static function members −

    #include <iostream>usingnamespace std;classBox{public:staticint objectCount;// Constructor definitionBox(double l =2.0,double b =2.0,double h =2.0){
             cout <<"Constructor called."<< endl;
             length = l;
             breadth = b;
             height = h;// Increase every time object is created
             objectCount++;}doubleVolume(){return length * breadth * height;}staticintgetCount(){return objectCount;}private:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a box};// Initialize static member of class Boxint Box::objectCount =0;intmain(void){// Print total number of objects before creating object.
       cout <<"Inital Stage Count: "<<Box::getCount()<< endl;
    
       Box Box1(3.3,1.2,1.5);// Declare box1
       Box Box2(8.5,6.0,2.0);// Declare box2// Print total number of objects after creating object.
       cout <<"Final Stage Count: "<<Box::getCount()<< endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Inital Stage Count: 0
    Constructor called.
    Constructor called.
    Final Stage Count: 2
    

    Use Cases for Static Members

    Here are the following use cases:

    • A singleton pattern is a design pattern that makes sure that a class has only one instance and provides a global point of access to it. Here static members are perfect for implementing this pattern because they allow to maintenance of a single shared instance of the class.
    • Static members are often used to manage shared resources or counters that should be shared across all instances of a class.
    • Static members can be used to store global configuration settings or constants, useful for managing a pool of resources (e.g., a cache, database connection pool, etc.) and implementing a logging system that is shared across instances. which is shared across all instances of a class.
    • Static members can be used for Tracking Method calls.
  • C++ Class Access Modifiers

    C++ access modifiers are used for data hiding implementation. Data hiding is one of the important features of object-oriented programming, which allows the functions of a program to access directly the internal representation of a class type.The access restriction to the class members is specified by the labeled public, private, and protected sections within the class body. The keywords public, private, and protected are called access specifiers.

    A class can have multiple public, protected, or private labeled sections. Each section remains in effect until either another section label or the closing right brace of the class body is seen. The default access for members and classes is private.

    classBase{public:// public members go hereprotected:// protected members go hereprivate:// private members go here};

    Public Access Modifier

    The public access modifier defines public data members and member functions that are accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member function.

    Example

    The following example demonstrates the use of public access modifier −

    #include <iostream>usingnamespace std;classLine{public:double length;voidsetLength(double len );doublegetLength(void);};// Member functions definitionsdoubleLine::getLength(void){return length ;}voidLine::setLength(double len){
       length = len;}// Main function for the programintmain(){
       Line line;// set line length
       line.setLength(6.0); 
       cout <<"Length of line : "<< line.getLength()<<endl;// set line length without member function
       line.length =10.0;// OK: because length is public
       cout <<"Length of line : "<< line.length <<endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Length of line : 6
    Length of line : 10
    

    Private Access Modifier

    The private access modifier defines private data members and member functions that cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.

    By default all the members of a class would be private, for example in the following class width is a private member, which means until you label a member, it will be assumed a private member.

    Example

    The following example demonstrates the use of private access modifier −

    classBox{double width;public:double length;voidsetWidth(double wid );doublegetWidth(void);};

    Practically, we define data in private section and related functions in public section so that they can be called from outside of the class as shown in the following program.

    #include <iostream>usingnamespace std;classBox{public:double length;voidsetWidth(double wid );doublegetWidth(void);private:double width;};// Member functions definitionsdoubleBox::getWidth(void){return width ;}voidBox::setWidth(double wid ){
       width = wid;}// Main function for the programintmain(){
       Box box;// set box length without member function
       box.length =10.0;// OK: because length is public
       cout <<"Length of box : "<< box.length <<endl;// set box width without member function// box.width = 10.0; // Error: because width is private
       box.setWidth(10.0);// Use member function to set it.
       cout <<"Width of box : "<< box.getWidth()<<endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Length of box : 10
    Width of box : 10
    

    Protected Access Modifier

    The protected access modifier defines protected data members and member functions that are very similar to a private member, but it provides one additional benefit that they can be accessed in child classes, which are called derived classes.

    You will learn derived classes and inheritance in next chapter. For now you can check following example where I have derived one child class SmallBox from a parent class Box.

    Example

    Following example is similar to above example and here width member will be accessible by any member function of its derived class SmallBox.

    #include <iostream>usingnamespace std;classBox{protected:double width;};classSmallBox:Box{// SmallBox is the derived class.public:voidsetSmallWidth(double wid );doublegetSmallWidth(void);};// Member functions of child classdoubleSmallBox::getSmallWidth(void){return width ;}voidSmallBox::setSmallWidth(double wid ){
       width = wid;}// Main function for the programintmain(){
       SmallBox box;// set box width using member function
       box.setSmallWidth(5.0);
       cout <<"Width of box : "<< box.getSmallWidth()<< endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Width of box : 5
  • C++ Class Member Functions

    A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.

    Let us take previously defined class to access the members of the class using a member function instead of directly accessing them −

    classBox{public:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a boxdoublegetVolume(void);// Returns box volume};

    Defining Class Member Functions

    Member functions can be defined within the class definition or separately using scope resolution operator, : −. Defining a member function within the class definition declares the function inline, even if you do not use the inline specifier. So either you can define Volume() function as below −

    Defining Member Function inside the Class

    classBox{public:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a boxdoublegetVolume(void){return length * breadth * height;}};

    Defining Member Function outside of the Class

    If you like, you can define the same function outside the class using the scope resolution operator (::) as follows −

    doubleBox::getVolume(void){return length * breadth * height;}

    Here, only important point is that you would have to use class name just before :: operator.

    Calling (Accessing) Member Functions

    A member function will be called using a dot operator (.) on a object where it will manipulate data related to that object only as follows −

    Box myBox;// Create an object
    
    myBox.getVolume();// Call member function for the object

    Example

    Let us put above concepts to set and get the value of different class members in a class −

    #include <iostream>usingnamespace std;classBox{public:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a box// Member functions declarationdoublegetVolume(void);voidsetLength(double len );voidsetBreadth(double bre );voidsetHeight(double hei );};// Member functions definitionsdoubleBox::getVolume(void){return length * breadth * height;}voidBox::setLength(double len ){
       length = len;}voidBox::setBreadth(double bre ){
       breadth = bre;}voidBox::setHeight(double hei ){
       height = hei;}// Main function for the programintmain(){
       Box Box1;// Declare Box1 of type Box
       Box Box2;// Declare Box2 of type Boxdouble volume =0.0;// Store the volume of a box here// box 1 specification
       Box1.setLength(6.0); 
       Box1.setBreadth(7.0); 
       Box1.setHeight(5.0);// box 2 specification
       Box2.setLength(12.0); 
       Box2.setBreadth(13.0); 
       Box2.setHeight(10.0);// volume of box 1
       volume = Box1.getVolume();
       cout <<"Volume of Box1 : "<< volume <<endl;// volume of box 2
       volume = Box2.getVolume();
       cout <<"Volume of Box2 : "<< volume <<endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Volume of Box1 : 210
    Volume of Box2 : 1560
  • C++ Classes and Objects

    The main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types.

    A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.

    C++ Class Definitions

    When you define a class, you define a blueprint for a data type. This doesn’t actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.

    A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the keyword class as follows −

    classBox{public:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a box};

    The keyword public determines the access attributes of the members of the class that follows it. A public member can be accessed from outside the class anywhere within the scope of the class object. You can also specify the members of a class as private or protected which we will discuss in a sub-section.

    Define C++ Objects

    A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box −

    Box Box1;// Declare Box1 of type Box
    Box Box2;// Declare Box2 of type Box

    Both of the objects Box1 and Box2 will have their own copy of data members.

    Accessing the Data Members

    The public data members of objects of a class can be accessed using the direct member access operator (.). Let us try the following example to make the things clear −

    #include <iostream>usingnamespace std;classBox{public:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a box};intmain(){
       Box Box1;// Declare Box1 of type Box
       Box Box2;// Declare Box2 of type Boxdouble volume =0.0;// Store the volume of a box here// box 1 specification
       Box1.height =5.0; 
       Box1.length =6.0; 
       Box1.breadth =7.0;// box 2 specification
       Box2.height =10.0;
       Box2.length =12.0;
       Box2.breadth =13.0;// volume of box 1
       volume = Box1.height * Box1.length * Box1.breadth;
       cout <<"Volume of Box1 : "<< volume <<endl;// volume of box 2
       volume = Box2.height * Box2.length * Box2.breadth;
       cout <<"Volume of Box2 : "<< volume <<endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Volume of Box1 : 210
    Volume of Box2 : 1560
    

    It is important to note that private and protected members can not be accessed directly using direct member access operator (.). We will learn how private and protected members can be accessed.

    Classes and Objects in Detail

    So far, you have got very basic idea about C++ Classes and Objects. There are further interesting concepts related to C++ Classes and Objects which we will discuss in various sub-sections listed below −

    Sr.NoConcept & Description
    1Class Member FunctionsA member function of a class is a function that has its definition or its prototype within the class definition like any other variable.
    2Class Access ModifiersA class member can be defined as public, private or protected. By default members would be assumed as private.
    3Constructor & DestructorA class constructor is a special function in a class that is called when a new object of the class is created. A destructor is also a special function which is called when created object is deleted.
    4Copy ConstructorThe copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously.
    5Friend Functionsfriend function is permitted full access to private and protected members of a class.
    6Inline FunctionsWith an inline function, the compiler tries to expand the code in the body of the function in place of a call to the function.
    7this PointerEvery object has a special pointer this which points to the object itself.
    8Pointer to C++ ClassesA pointer to a class is done exactly the same way a pointer to a structure is. In fact a class is really just a structure with functions in it.
    9Static Members of a ClassBoth data members and function members of a class can be declared as static.
  • C++ Object Oriented

    The prime purpose of C++ programming was to add object orientation to the C programming language, which is in itself one of the most powerful programming languages.

    The core of the pure object-oriented programming is to create an object, in code, that has certain properties and methods. While designing C++ modules, we try to see whole world in the form of objects. For example a car is an object which has certain properties such as color, number of doors, and the like. It also has certain methods such as accelerate, brake, and so on.

    There are a few principle concepts that form the foundation of object-oriented programming −

    Object

    This is the basic unit of object oriented programming. That is both data and function that operate on data are bundled as a unit called as object.

    Class

    When you define a class, you define a blueprint for an object. This doesn’t actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.

    Abstraction

    Data abstraction refers to, providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details.

    For example, a database system hides certain details of how data is stored and created and maintained. Similar way, C++ classes provides different methods to the outside world without giving internal detail about those methods and data.

    Encapsulation

    Encapsulation is placing the data and the functions that work on that data in the same place. While working with procedural languages, it is not always clear which functions work on which variables but object-oriented programming provides you framework to place the data and the relevant functions together in the same object.

    Inheritance

    One of the most useful aspects of object-oriented programming is code reusability. As the name suggests Inheritance is the process of forming a new class from an existing class that is from the existing class called as base class, new class is formed called as derived class.

    This is a very important concept of object-oriented programming since this feature helps to reduce the code size.

    Polymorphism

    The ability to use an operator or function in different ways in other words giving different meaning or functions to the operators or functions is called polymorphism. Poly refers to many. That is a single function or an operator functioning in many ways different upon the usage is called polymorphism.

    Overloading

    The concept of overloading is also a branch of polymorphism. When the exiting operator or function is made to operate on new data type, it is said to be overloaded.

  • Smart Pointers in C++

    smart pointer is a class template that wraps around a raw pointer. It is used in memory management to clear the dynamically allocated memory automatically when it is no longer needed. This prevents memory leaks and dangling pointers. They are implemented as templates in the Standard Template Library (STL) (<memory> header).

    Memory Leak: In C++, we need to manually clear the dynamically allocated memory. Memory leak occurs when the dynamically allocated memory is not cleared.
    Dangling Pointer: It is a pointer that points to the memory address that has been cleared earlier but it still pointing to that deallocated memory address.

    Here is an example of memory leak and dangling pointer where the ptr pointer causes a memory leak and the ptr2 pointer becomes a dangling pointer.

    #include <iostream>usingnamespace std;intmain(){int*ptr1 =newint(42);// allocating memory
        cout <<"ptr1 pointer Value: "<<*ptr1 << endl;// Here memory leak occurs as we have// not freed the allocated memoryint*ptr2 =newint(100);// allocating memorydelete ptr2;// clearing the memory// accessing freed memory
        cout <<"ptr2 pointer value: "<<*ptr2 << endl;// dangling pointerreturn0;}

    The output of the above code is as follows −

    ptr1 pointer Value: 42
    ptr2 pointer value: 1465330567
    

    Types of Smart Pointers

    Smart pointers are of 4 types that are mentioned below. You need to use <memory> header to use these smart pointers −

    The auto_ptr Pointer

    The auto_ptr is a type of smart pointer that automatically manages memory. It is now deprecated since C++11, and removed in C++17 as it uses copy assignments operator to transfer ownership automatically without warning and the original pointer becomes null unexpectedly. This leads to unexpected null pointer access and program can crash.

    Here is a simple example of auto_ptr where we are printing the value of ptr1 and ptr2. It will show a warning in the output as it has been deprecated −

    #include <iostream>#include <memory>usingnamespace std;intmain(){
        auto_ptr<int>ptr1(newint(100));
        cout <<"ptr1 value: "<<*ptr1 << endl;
    
        auto_ptr<int> ptr2 = ptr1;
        cout <<"ptr2 value: "<<*ptr2 << endl;return0;}

    The output of the above code is as follows. As we can see here it gives a warning that auto_pointer has been deprecated −

    main.cpp: In function 'int main()':
    main.cpp:7:5: warning: 'template<class> class std::auto_ptr' is deprecated: use 
        'std::unique_ptr' instead [-Wdeprecated-declarations]
        7 |     auto_ptr<int> ptr1(new int(100));
    
    ptr1 value: 100
    ptr2 value: 100
    

    The unique_ptr Pointer

    The unique_ptr is a smart pointer that owns only one object at a time. It does not copy the pointers from one pointer to other. It transfers its ownership using std::move() function and automatically deletes the memory when the pointer goes out of scope. It solves the problem of auto_ptr and prevent memory leaks. You can use unique_ptr for single ownership.

    Below is an example of unique_ptr where the pointer ptr1 transfers its ownership to pointer ptr2 to print the pointer value −

    #include <iostream>#include <memory>usingnamespace std;intmain(){
        unique_ptr<int> ptr1 =make_unique<int>(200);
        cout <<"ptr1 value: "<<*ptr1 << endl;
    
        unique_ptr<int> ptr2 =move(ptr1);
        cout <<"ptr2 value: "<<*ptr2 << endl;return0;}

    The output of the above code is as follows:

    ptr1 value: 200
    ptr2 value: 200
    

    The shared_ptr Pointer

    shared_ptr is a smart pointer that allows multiple pointers to share ownership of the same object using reference counting, unlike unique_ptr where only one pointer can have the ownership of an object.

    It maintains a reference count to keep a track of number of pointers sharing one object. The reference count is decreased when a shared_ptr is destroyed and the object is automatically deleted when count reaches zero. You can use shared_ptr when you need multiple owners of the same object.

    Here is an example of shared_ptr where both the pointers share the same object −

    #include <iostream>#include <memory>usingnamespace std;intmain(){
        shared_ptr<int> ptr1 =make_shared<int>(300);
        cout <<"ptr1 value: "<<*ptr1 << endl;
        cout <<"Reference count: "<< ptr1.use_count()<< endl;
    
        shared_ptr<int> ptr2 = ptr1;// Both can access the object
        cout <<"\nAfter sharing:"<< endl;
        cout <<"ptr1 value: "<<*ptr1 << endl;
        cout <<"ptr2 value: "<<*ptr2 << endl;
        cout <<"Reference count: "<< ptr1.use_count()<< endl;return0;}

    The output of the above code is as follows −

    ptr1 value: 300
    Reference count: 1
    
    After sharing:
    ptr1 value: 300
    ptr2 value: 300
    Reference count: 2
    

    The weak_ptr Pointer

    weak_ptr is a non-owning pointer to an object. Unlike shared_ptr, it does not increase the reference count of an object, and it can detect if the object has been destroyed. You can access the object using weak_ptr, but first you must lock the weak_ptr. By locking you get a temporary shared_ptr. It is used to avoid the circular dependency between shared_ptr objects.

    Here is an example of accessing an object value 400 using weak_ptr observer −

    #include <iostream>#include <memory>usingnamespace std;intmain(){
        shared_ptr<int> owner =make_shared<int>(400);
        weak_ptr<int> observer = owner;
        cout <<"shared_ptr reference count: "<< owner.use_count()<< endl;// Lock to use weak_ptrif(auto locked = observer.lock()){
            cout <<"Object value: "<<*locked << endl;}
        owner.reset();
        cout << endl;return0;}

    The output of the above code is as follows −

    shared_ptr reference count: 1
    Object value: 400
    

    Pointer vs Smart Pointer

    The following table differentiates between a pointer and a smart pointer −

    PointerSmart Pointer
    A pointer stores memory address of another variable or object.A smart pointer is a class template that wraps around a raw pointer and used for automatic memory management.
    Manually new and delete is called to allocate and deallocate memory.It uses RAII(Resource Acquisition is Initialization) principles to automatically manage memory for allocation and deallocation.
    It creates chances of memory leak and dangling pointers.No risk of memory leaks or dangling pointers.
    There is no feature to track the numbers of pointers pointing to an object.Here, shared_ptr maintains a reference counter to track the number of pointers pointing to the same object.
    It is not destroyed when it goes out of its scope.It gets automatically destroyed when it goes out of scope.

    Conclusion

    Smart pointers in C++ help in automatic memory management that solves the problem of memory leak and dangling pointers. There are four types of smart pointers: auto_ptrunique_ptrshared_ptr, and weak_ptr, out of which the auto_ptr has been deprecated.

  • C++ Modify Pointers

    In C++ programming, a pointer is a variable that stores the memory address of another variable. Instead of holding a data value directly, a pointer holds the memory location of the value.

    What is Modifying Pointers in C++?

    Modifying the pointer value in C++ refers to the process of changing the memory address or changing the value stored at the memory address the pointer is pointing to.

    Approach to Modify Pointers

    Begin with declaring a pointer variable and initializing it. To modify the pointer’s value, assign a new address to it. If using dynamic memory, allocate new memory using new and assign its address to the pointer. After modifying the pointer, you can dereference it to access or modify the value at the new address.

    If you allocate memory dynamically, ensure to release it using delete to prevent memory leaks.

    Example of Modifying Pointers

    Here’s a simple example illustrating the modification of the pointers values −

    #include <iostream>usingnamespace std;intmain(){int var1 =10;int var2 =20;int* ptr =&var1;// ptr points to var1
       cout <<"Value pointed by ptr: "<<*ptr << endl; 
    
       ptr =&var2;// Modify ptr to point to var2
       cout <<"Value pointed by ptr after modification: "<<*ptr << endl;// Dynamic memory allocationint* dynamicPtr =newint(30);
       ptr = dynamicPtr;// Modify ptr to point to dynamic memory
       cout <<"Value pointed by ptr after dynamic allocation: "<<*ptr << endl;// Clean up dynamic memorydelete dynamicPtr;return0;}

    Output

    Value pointed by ptr: 10
    Value pointed by ptr after modification: 20
    Value pointed by ptr after dynamic allocation: 30
    

    Explanation

    • Firstly, we declared (var1 and var2) and initialized the variable with values 10 and 20.
    • Then declared the pointer named ptr, which holds the address of an integer, var1 using the address-of operator (&).
    • *ptr, the value at the address stored in ptr is accessed using the dereference operator (*).
    • ptr = &var2; The pointer ptr is modified to point to var2. Now, when dereferenced, it will access the value of var2, which is 20, so this prints 20.
    • Now for Dynamic Memory Allocation, int* dynamicPtr = new int(30); Memory is dynamically allocated using new and initialized to 30, Where the address of this memory is stored in the pointer dynamicPtr.
    • ptr = dynamicPtr; in this ptr is modified to point to the dynamically allocated memory (dynamicPtr). When dereferenced, it will print 30.
    • delete dynamicPtr; This is used to prevent memory leaks.
  • C++ Dereferencing

    In C++, dereferencing is the process that helps in accessing the value that a pointer points to. Where pointers store the memory address of that particular value. To access or modify the value stored at that address, you can use the dereference operator denoted by (*).

    Dereferencing to Read a Value

    Here is the syntax to access the value, which is stored at the address the pointer points to −

    Type value =*pointer;// Gets the value at the address pointed to by the pointer

    Dereferencing to Modify a Value

    Syntax of dereference operator to modify the value at the address the pointer points to −

    *pointer = newValue;// Sets the value at the address pointed to by the pointer

    Example of C++ Dereferencing

    Heres a simple example illustrating dereferencing in C++ −

    #include <iostream>usingnamespace std;intmain(){int number =42;// A normal integer variableint* ptr =&number;// Pointer that holds the address of 'number'// Dereferencing to read the value
       cout <<"Original Value: "<<*ptr << endl;// Dereferencing to modify the value*ptr =100;  
       cout <<"Modified Value: "<< number << endl;return0;}

    Output

    Original Value: 42
    Modified Value: 100
    

    Explanation

    • Firstly, we declared an integer variable named number and initialized it with the value 42.
    • Declared a pointer ptr of data type integer. The pointer is assigned the address of the number using the address-of operator &. which means ptr will point to the location of the memory address of a number.
    • Now, we used the dereference operator to access the value stored at the address pointed to by ptr.
    • *ptr = 100; This line uses the dereference operator again, but this time to assign a new value.

    References vs Dereference

    ReferencesDereference
    DefinitionReference is a variable for another variable, which allows you to access or modify the original variable without using its name directly.Dereferencing is the process of accessing the value stored at the memory address held by a pointer.
    Symbol& (used in declaration)* (used in expression)
    SyntaxdataType& referenceName = existingVariable;dataType pointerVariable = *pointerName;

    Example Showing both Reference and Dereference

    Heres an example illustrating both reference and dereference in a code.

    #include <iostream>usingnamespace std;intmain(){int number =42;// Pointer holding the address of 'number'int* ptr =&number;// Reference to 'number'int& ref = number;// Using pointer to read the value (dereferencing ptr)
       cout <<"Original Value (pointer): "<<*ptr << endl;// Using reference to read the value
       cout <<"Original Value (reference): "<< ref << endl;// Modifying the value through the pointer (dereferencing ptr)*ptr =100;  
       cout <<"Modified Value (pointer): "<< number << endl;  
       cout <<"Modified Value (reference): "<< ref << endl;// Modifying the value through the reference
       ref =200;  
       cout <<"Modified Value (reference): "<< number << endl;  
       cout <<"Modified Value (pointer): "<<*ptr << endl;return0;}

    Output

    Original Value (pointer): 42
    Original Value (reference): 42
    Modified Value (pointer): 100
    Modified Value (reference): 100
    Modified Value (reference): 200
    Modified Value (pointer): 200
  • C++ Pointers

    C++ pointers are easy and fun to learn. Some C++ tasks are performed more easily with pointers, and other C++ tasks, such as dynamic memory allocation, cannot be performed without them.

    As you know every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory. Consider the following which will print the address of the variables defined −

    #include <iostream>usingnamespace std;intmain(){int  var1;char var2[10];
    
       cout <<"Address of var1 variable: ";
       cout <<&var1 << endl;
    
       cout <<"Address of var2 variable: ";
       cout <<&var2 << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Address of var1 variable: 0xbfebd5c0
    Address of var2 variable: 0xbfebd5b6
    

    What are Pointers?

    pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is −

    type *var-name;

    Here, type is the pointer’s base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration −

    int*ip;// pointer to an integerdouble*dp;// pointer to a doublefloat*fp;// pointer to a floatchar*ch     // pointer to character

    The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.

    Using Pointers in C++

    There are few important operations, which we will do with the pointers very frequently. (a) We define a pointer variable. (b) Assign the address of a variable to a pointer. (c) Finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations −

    #include <iostream>usingnamespace std;intmain(){int  var =20;// actual variable declaration.int*ip;// pointer variable 
    
       ip =&var;// store address of var in pointer variable
    
       cout <<"Value of var variable: ";
       cout << var << endl;// print the address stored in ip pointer variable
       cout <<"Address stored in ip variable: ";
       cout << ip << endl;// access the value at the address available in pointer
       cout <<"Value of *ip variable: ";
       cout <<*ip << endl;return0;}

    When the above code is compiled and executed, it produces result something as follows −

    Value of var variable: 20
    Address stored in ip variable: 0xbfc601ac
    Value of *ip variable: 20
    

    Pointers in C++

    Pointers have many but easy concepts and they are very important to C++ programming. There are following few important pointer concepts which should be clear to a C++ programmer −

    Sr.NoConcept & Description
    1Null PointersC++ supports null pointer, which is a constant with a value of zero defined in several standard libraries.
    2Pointer ArithmeticThere are four arithmetic operators that can be used on pointers: ++, –, +, –
    3Pointers vs ArraysThere is a close relationship between pointers and arrays.
    4Array of PointersYou can define arrays to hold a number of pointers.
    5Pointer to PointerC++ allows you to have pointer on a pointer and so on.
    6Passing Pointers to FunctionsPassing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.
    7Return Pointer from FunctionsC++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well.
  • Unions in C++

    In C++, a union is a user-defined data type that allows you to store different data types in the same memory location. However, the union can store only one of its member variables at a time, which means that if you assign a value to one member, the previous value stored in another member is overwritten. Where the size of a union is determined by the size of its largest member.

    Union Declaration

    To declare a union, use the union keyword followed by the tag_name (union name) and then declare the union members with their data types inside the curly brackets. Close the declaration with a semicolon.

    Below is the syntax to declare a union −

    union UnionName {
      dataType1 member1;
      dataType2 member2;// more members};

    Example

    Here’s a short example based on the above syntax to declare a union −

    union UnionName {int intValue;// Member for integer valuefloat floatValue;// Member for float valuechar charValue;// Member for character value};

    Declaring Union Variable

    After declaring a union, you need to declare its variable to access and manipulate its members.

    Below is the syntax to declare a union variable −

    union_name variable;

    Accessing Union Members

    You can access union members using the dot operator (.) after declaring a union variable. 

    Below is the syntax to access union members –

    union_variable.member
    

    Example of C++ Union

    Here’s a full example of a union demonstrating it’s working −

    #include <iostream>#include <cstring>usingnamespace std;union Data {int intValue;// Member for integer valuefloat floatValue;// Member for float valuechar strValue[50];// Member for string value};intmain(){// Defining a union variable
      Data data;
    
      data.intValue =2006;
      cout <<"TutorialsPoint: Founded in "<< data.intValue << endl;// overwrites the previous integer value
      data.floatValue =5.75f;
      cout <<"My Float value is: "<< data.floatValue << endl;// overwrites the previous float valuestrcpy(data.strValue,"Hello TutorialsPoint Learner");
      cout << data.strValue << endl;// Accessing the integer after assigning a string
      cout <<"Integer after string assignment: "<< data.intValue << endl;// Undefined behaviorreturn0;}

    When the above code is compiled and executed, it produces the following result −

    TutorialsPoint: Founded in 2006
    My Float value is: 5.75
    Hello TutorialsPoint Learner
    Integer after string assignment: 1819043144
    

    Explanation

    The above-given example demonstrates the use of a union, how it is created and accessed,

    • Firstly, a union named Data is defined with three members: int intValue, float floatValue, char strValue[50], where only one of these members can hold a value at any given time. 
    • As the size of the union is determined by the largest member so in this case (the char array).
    • A union variable data is declared in the int main() body.
    • To assign and access members, all the members are assigned their values by using “.” as data.intValue respectively.
    • For float value, the float member floatValue is assigned the value 5.75.
    • However, since a union can only hold one value at a time the previous value of intValue is overwritten, though it will still occupy the same memory space.
    • Now at last finally when the code attempts to print intValue after it has been overwritten by the string assignment. This leads to undefined behavior, the integer value is no longer valid, and accessing it may give unexpected results as given in the output.

    Anonymous Unions

    Anonymous unions are a special type of union which don’t have a name. This helps in simplifying code by allowing you to direct access to union members without specifying the union variable name.

    Syntax

    Here’s a simple syntax for Anonymous Union, which is declared without any name, allowing direct access to its members −

    union{
      dataType1 member1;
      dataType2 member2;// additional members...};

    Example

    Here’s an example of the above-based syntax for the anonymous union −

    #include <iostream>#include <cstring>usingnamespace std;// Use the standard namespaceintmain(){// Anonymous union declarationunion{int intValue;float floatValue;char strValue[50];};// Assigning an integer value
      intValue =2006;
      cout <<"Integer Value: "<< intValue << endl;// Assigning a float value (overwrites the previous integer value)
      floatValue =3.14 f;
      cout <<"Float Value: "<< floatValue << endl;// Assigning a string value (overwrites the previous float value)strcpy(strValue,"Hello, TutorialsPoint Learner!");
      cout <<"String Value: "<< strValue << endl;// Accessing the integer after string assignment (undefined behavior)
      cout <<"Integer after string assignment: "<< intValue << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Integer Value: 2006
    Float Value: 3.14
    String Value: Hello, TutorialsPoint Learner!
    Integer after string assignment: 1819043144
    

    Union-like Classes

    In C++ a union-like class is defined as a class that includes at least one anonymous union as a member. The data members defined within these anonymous unions are known as variant members. It is the data structures that encapsulate the concept of a union but provide additional features for type safety and usability. 

    These typically use a combination of member variables and a mechanism (like an enumerator) to track which type is currently active.

    Syntax

    Here’s a basic syntax for Union-like classes where the class keyword is used to define the class, followed by the class name class name (here, UnionLikeClass)

    classUnionLikeClass{public:union{
        dataType1 member1;// Member of type dataType1
        dataType2 member2;// Member of type dataType2// additional members...};};

    Example

    Here’s an example of Union-like classes based on the above syntax:

    #include <iostream>#include <cstring>usingnamespace std;classUnionLikeClass{public:// Anonymous union declarationunion{int intValue;// Member for integer valuefloat floatValue;// Member for float valuechar strValue[50];// Member for string value};// Method to display the current valuevoiddisplay(){
        cout <<"Integer Value: "<< intValue << endl;
        cout <<"Float Value: "<< floatValue << endl;
        cout <<"String Value: "<< strValue << endl;}};intmain(){// Creating an instance of UnionLikeClass
      UnionLikeClass data;
    
      data.intValue =2006;
      cout <<"TutorialsPoint: Founded in "<< data.intValue << endl;
    
      data.floatValue =3.14f;
      cout <<"Assigned Float Value: "<< data.floatValue << endl;// Assigning a string value (overwrites the previous float value)strcpy(data.strValue,"Hello, Union Like Class!");
      cout <<"Assigned String Value: "<< data.strValue << endl;// Accessing the integer after string assignment (undefined behavior)
      cout <<"Integer after string assignment: "<< data.intValue << endl;// Undefined behaviorreturn0;}
    TutorialsPoint: Founded in 2006
    Assigned Float Value: 3.14
    Assigned String Value: Hello, Union Like Class!
    Integer after string assignment: 1819043144