copy constructor

closed account (SECMoG1T)
Hi, when passing a class parameter to a function using a const lvalue reference, am i required to provide a copy constructor for such a class to be used in argument construction?

Thanks in advance.
Passing by reference does not involve a copy. That's kind of the whole point. You're passing the reference to the original object and therefore are not creating a copy.

So no.

Also, you don't really have to supply a copy constructor anyway because the compiler will auto-generate one if you don't. The only time you need to is if the object cannot be trivially copied (ie: if you are manually managing memory or something)
It is also easy to test whether the copy constructor is called:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

class Foo {
    Foo( const Foo & ) = delete; // inaccessible and non-existing
public:
    Foo() = default;
    int boo() const { return 42; }
};

void bar( const Foo & x ) {
    std::cout << x.boo() << '\n';
}

int main() {
    Foo a;
    bar( a );
	return 0;
}
closed account (SECMoG1T)
ooh perfect now i get it, i was a little bit confused about the idea of argument construction, so it's like construction is only required when passing objects by value.

Thanks @Disch
closed account (SECMoG1T)
@Keskiverto you just read my mind hehe, the reason i was asking this is because i wanted to mark all my copy control members as deleted to prevent copying my class objects but i got worried about passing my objects as arguments to functions.

Thanks pal.
closed account (SECMoG1T)
What if i have my objects in a container such as a vector, will my deleted copy control members affect anything if i attempt to initialize a new container from an existing one or during assignment of such containers.
Last edited on
i attempt to initialize a new container from an existing one or during assignment of such containers.
Yes, you cannot copy from one to other. However, you will still be able to move (provided you have move constructor). Look at streams and unique_ptr behavior. They are both non-copyable, but moveable.
closed account (SECMoG1T)
@MiiNiPaa thanks a lot for the insight, so that means i should retain either my copy/move constor and assignment operators? coz right now i have all of them deleted 0:), also my class is a base class and i have a virtual destructor will it be affected?

Last edited on
Topic archived. No new replies allowed.