swap.h :

#pragma once

class Swap
{
public:
	Swap(void);
public:
	~Swap(void);
public:
	void SwapNumbers(int & number1, int & number2);
public:
	void SwapNumbersViaPointer(int * pNumber1, int * pNumber2);
	
};

swap.cpp :

#include "Swap.h"

Swap::Swap(void)
{
}

Swap::~Swap(void)
{
}

void Swap::SwapNumbers(int & number1, int & number2)
{
	int tmp = number2;
	number2 = number1;
	number1 = tmp;
}
void Swap::SwapNumbersViaPointer(int * pNumber1,int * pNumber2)
{
	int tmp = *pNumber1;
	*pNumber1 = *pNumber2;
	*pNumber2 = tmp;
}

start.cpp :

#include <iostream>
#include "Swap.h"
using namespace std;

int main()
{
	Swap swapper;
	int number1;
	int number2;
	cout << "enter two numbers to swap" << endl;
	
	cout << "enter first number" << endl;
	cin >> number1;
	cout << "enter second number" << endl;
	cin >> number2;

	swapper.SwapNumbers(number1,number2);
    
	cout << "number1 : " << number1 << endl;
	cout << "number2 : " << number2 << endl;


	cout << "using pointers to restore the numbers" << endl;
	swapper.SwapNumbersViaPointer(&number1,&number2);
     
	cout << "number1 : " << number1 << endl;
	cout << "number2 : " << number2 << endl;


	return 0;
}

output :

enter two numbers to swap
enter first number
23
enter second number
24
number1 : 24
number2 : 23
using pointers to restore the numbers
number1 : 23
number2 : 24
Press any key to continue . . .

Recommended Answers

All 6 Replies

Why do you have a class named Swap?

Why do you have a class named Swap?

i just created it using visual studio, it didnt matter if it is in class or not, but my question is what is the difference between the two swap method? if they are the same thing, why does the syntax of the language gives me two ways to the same thing?

>why does the syntax of the language gives me two ways to the same thing?
Pointers were inherited from C and references were added with C++ to support other C++ features. It's basically the same principle as structs and classes, except pointers and references are actually different in significant ways.

>except pointers and references are actually different in significant ways

Could you please mention some of those significant differences?

>Could you please mention some of those significant differences?
I could, but because I would be listing something that's equally well listed in any decent book on C++, I'll direct you there instead. Or you could check the C++ FAQ Lite, which I recall referring you to before.

>FAQ Lite, which I recall referring you to before,
i like the way you tell the things, your way of understanding does not require me to compile your sentences to my way of understanding as your words are like native code for my brain :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.