This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Friday, February 17, 2023

Short notes on : 1. static data members and static member functions 2. This pointer 3. Namespaces

 1. Static data members and static member functions:
    Static data members and static member functions are used in C++ to create class variables and functions that are shared by all objects for the class. A static data member is a variable that is associated with the class, not with any individual object of that class. Similarly, a static member function is a function that is associated with the class and can be called without an object of that class.

Syntax for declaring static data members and static member functions:

class MyClass {
public:
    static int myStaticData; // static data member
    static void myStaticFunction(); // static member function
};

int MyClass::myStaticData = 0; // static data member definition
void MyClass::myStaticFunction() { // static member function definition
    // implementation
}

2. This pointer:

The this pointer is a pointer that holds the memory address of the current object. It is a keyword in C++ that is used in class member functions to refer to the object that  called the function. It is useful in situations where a member function needs to access the object's data members or call member functions of the same object.

Syntax for using this pointer:

class MyClass {
public:
    void setValue(int value) {
        this->value = value; // using this pointer to set value
    }

    void printValue() {
        std::cout << "Value = " << this->value << std::endl; // using this pointer to print value
    }

private:
    int value;
};

3. Namespaces:

Namespaces are used in C++ to group related classes, functions, and variables under a common name. They are used to avoid naming conflicts between different libraries of modules in a program. A namespace can contain any valid C++ code, including class declarations, function definitions, variable declarations, and so on.

Syntax for using namespaces:

// declaring namespace
namespace myNamespace {
    int myVar;
    void myFunction();
}

// using namespace
using namespace myNamespace;

// accessing variables and functions in the namespace
int main() {
    myVar = 10;
    myFunction();
    return 0;
}

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget