Question about passing class as alias parameter in C++? [duplicate]
Possible Duplicate:
Why should the copy constructor accept its parameter by reference in C++?
I have the following code:
class Student {
private:
int no;
char name[14];
public:
开发者_开发百科 void display() const;
Student(const Student& student); // Line 1
};
I have read that class is a reference type, so why in Line 1 of the above code declared as alias.
Is Line 1
equivalent to: Student(const Student student);
?
I have read that class is a reference type
In C++, the assertion that “class is a reference type” makes no sense. You may have heard this in connection with C# but this is a completely different matter.
Consequently, the whole discussion is moot. To understand the syntax of copy constructors you first need to understand references (those do exist in C++) and classes in general. Grab a good C++ book for beginners.
First I would use
std::string name
instead of
char name[14]
and Student(const Student student);
is NOT the same as Student(const Student& student);
Student(const Student student) //is a copy
Student(const Student& student) // is a reference to the object
Classes are not reference types. You probably got that from C# or something. You have to add &
to a type name to make it a reference. So Student
is a student object, whereas Student&
is a reference to a Student
object.
It is not at all the same code.
Passing a parameter by reference will push the exact object on the function's argument stack. Passing one by value will push a copy.
If you declare your copy constructor without the reference, you'll get an infinite loop, as the program will try to create a copy calling the copy constructor, which in turn will try to create a copy and so on.
Class is not a reference type. It is a user defined type in C++. When ever we use &
as a part of (member) function argument(s), it means we receive a reference of the parameter(s) passed. Any modification made to the reference will actually modify the passed parameter itself. While in the other case, a copy of the object is made.
Class is a reference type in many managed languages (like Java or C#). It is not the case however in C++. If you write Student(const Student student);
it means you define a constructor taking one parameter of type Student by value. In essence copying the object into the scope of the function.
Also in C++ we call syntax like this: Student(const Student& student);
passing by reference, not alias (in essence the same, but it may be confusing when reading up on some related subject).
精彩评论