Pointers, Functions, Classes in C++

Pointers, Functions, Classes in C++

Pointers, Functions, Classes in C++

Pointers and Functions:


#include <iostream>

void modifyValue(int* ptr) {
    *ptr = 20; // Changes the value stored at the address pointed to by ptr
}

int main() {
    int num = 10;
    std::cout << "Before function call: " << num << std::endl;
    modifyValue(&num); // Passing the address of num
    std::cout << "After function call: " << num << std::endl;
    return 0;
}
    

Returning Pointers from Functions:


#include <iostream>

int* createArray() {
    int* arr = new int[5]; // Dynamically allocating memory for an array
    for (int i = 0; i < 5; ++i) {
        arr[i] = i + 1;
    }
    return arr; // Returning the pointer to the first element of the array
}

int main() {
    int* ptr = createArray();
    for (int i = 0; i < 5; ++i) {
        std::cout << ptr[i] << " ";
    }
    delete[] ptr; // Deallocating the memory allocated for the array
    return 0;
}
    

Pointers and Classes:


#include <iostream>

class MyClass {
private:
    int data;
public:
    void setData(int value) {
        data = value;
    }
    int getData() {
        return data;
    }
};

int main() {
    MyClass obj;
    MyClass* ptr = &obj; // Pointer to an object of MyClass
    ptr->setData(10); // Accessing member function using pointer
    std::cout << "Data stored in object: " << ptr->getData() << std::endl;
    return 0;
}
    

this Pointer:


#include <iostream>

class MyClass {
private:
    int data;
public:
    void setData(int value) {
        this->data = value; // 'this' pointer refers to the object itself
    }
    int getData() {
        return this->data;
    }
};

int main() {
    MyClass obj;
    obj.setData(10);
    std::cout << "Data stored in object: " << obj.getData() << std::endl;
    return 0;
}
    

Understanding pointers and their usage with functions and classes is essential for efficient memory management and object-oriented programming in C++.

Comments

Popular posts from this blog

Ethereal vs Wireshark Comparison

Tshark vs Wireshark Comparison