Hi. I'm new to C++, and I'm having problems understanding a certain type of function argument. I wrote this code to try and understand it, and it didn't help much. :)

#include <iostream>
using namespace std;

class TestClass {
      public:
             int a ( TestClass arg );
             int b ( TestClass & arg );
};
int TestClass :: a ( TestClass arg ) {
    cout << &arg << "\n";
}
int TestClass :: b ( TestClass & arg ) {
    cout << &arg;
}

int main () {
    TestClass example;

    example.a ( example );
    example.b ( example );
    
    return 0;
}

As I understand it, the reference operator (&) represents the memory location of the value of a variable. I'm also sure I read somewhere that you can't pass a class as a function argument.

So in main, I make an example TestClass, and pass it to the two method of that. One of them takes, as the argument, just the value as a type of that class, and the other puts the reference operator in it. Both then output the reference part.

In 'b', what am I actually defining as the argument? O_o And what's the difference between the two? The 'this' value matches 'b' but not 'a'. Why?

Thanks! :D

Recommended Answers

All 2 Replies

>>I'm also sure I read somewhere that you can't pass a class as a function argument.

You must have misread it. The class in a is a new instance of the class while the class in b is the same instance. In a the class is passes by value, meaning that the compiler duplicated it and gives it another this pointer.

>>I'm also sure I read somewhere that you can't pass a class as a function argument.

You must have misread it. The class in a is a new instance of the class while the class in b is the same instance. In a the class is passes by value, meaning that the compiler duplicated it and gives it another this pointer.

Oooh. So if you need to pass a specific instance of a class, you use the & operator in the argument definition? Cheers! Does that mean that passing 'example' as the argument to 'a' doesn't really do anything, if the compiler just duplicates the class, and passing any instance of that class would have exactly the same effect?

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.