Pointer Reference Increment

#include <iostream>
using namespace std;

class Distance;

class Point{
private:
    int x;

public:
    Point(int v) : x(v) {}
    friend void sumValues(const Point&,const Distance&);
};

class Distance{
private:
    int d;

public:
     Distance(int v) : d(v) {}
     friend void sumValues(const Point&,const Distance&);
};

void sumValues(const Point& p,const Distance& dist){
    cout <<"Sum=" <<(p.x +dist.d);
}
// Define incrementPtr(int* x)
// Increment the value pointed to by x
// Do nothing if x is nullptr
void incrementPtr(int* x){
    if(x!=nullptr){
        (*x)++;
    }
}
// Define incrementRef(int& x)
// Increment the referenced value
void incrementRef(int& x){
    x++;
}
int main() {
    int n;
    std::cin >> n;

    int a = n;
    incrementPtr(&a);
    std::cout << "After incrementPtr: " << a << "\n";

    int b = n;
    incrementRef(b);
    std::cout << "After incrementRef: " << b;

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5

Expected Output

After incrementPtr: 6 After incrementRef: 6