poy
poy

Reputation: 10507

c++ classes can only be passed by reference

Is there a way I can make my custom class be passed by reference only?

Basically, I have the following class:

class A{
private:
  int _x;
public:
  A(int y){
    _x = y;
  }
};

Can I make it to where I can ONLY pass it by reference? And it will throw a compile time error otherwise?

Upvotes: 1

Views: 215

Answers (3)

clanmjc
clanmjc

Reputation: 299

Yes declaring the copy constructor private (but still implementing it) allows friend functions or friend classes to still use the private function/members of the class, therefore, the copy constructor would still be accessible. Which is why you declare it private and do not implement it.

Upvotes: 2

JaredPar
JaredPar

Reputation: 754545

Several people have suggested making the copy constructor private. This is a mostly good solution to the problem however it's not complete. It still allows the type itself to accidentally pass itself by value. A more thorough solution is to declare the copy constructor private and then never implement it.

class A{
private:
  // Prevent value copying
  A(const A&);

  int _x;
public:
  A(int y){
    _x = y;
  }
};

Note: As @DeadMG points out, in C++11 using delete is preferred.

A(const A&) = delete;

Upvotes: 3

Puppy
Puppy

Reputation: 146910

You can prevent copying by declaring the copy constructor as private (or deleted in C++11).

Upvotes: 10

Related Questions