Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass by const reference of class

Tags:

c++

void foo(const ClassName &name)
{
    ...
}

How can I access the method of class instance name?

name.method() didn't work. then I tried:

void foo(const ClassName &name)
{
    ClassName temp = name;
    ... ....
}

I can use temp.method, but after foo was executed, the original name screwed up, any idea? BTW, the member variable of name didn't screwed up, but it was the member variable of subclass of class screwed up.

like image 954
small_potato Avatar asked Dec 29 '22 16:12

small_potato


1 Answers

Going by the description you provided, it looks like method() in ClassName is a non-const method. If you try to call a non-const method on a const object compiler will throw an error. When you did ClassName temp = name; you created a copy of the variable into a temporary non-const object temp. You can call any method on this object but since it is a copy, the modification done on this object will not be reflected in name object.

EDIT

The best way to solve this, is to make the ClassName::method const if it doesn't modify any member variables. If it does, then you should not take your parameter in function foo as a const-reference. You should take parameter as a non-const reference.

like image 56
Naveen Avatar answered Jan 14 '23 11:01

Naveen