1

in this class

class Foo {
public:
  Foo(){}
  Foo(Foo const &) {}
};

when would Foo(Foo const &) ever be called? I do not understand this kind of constructor

  • 1
    http://stackoverflow.com/questions/2168201/what-is-a-copy-constructor-in-c – deviantfan Nov 24 '16 at 07:13
  • 1
    You'll probably find [**this page**](http://en.cppreference.com/w/cpp/language/copy_constructor) informative. – WhozCraig Nov 24 '16 at 07:13
  • 1
    This page also has a good general explanation of const, with your specific question in the section titled "Where it Gets Messy - in Parameter Passing" : http://duramecho.com/ComputerInformation/WhyHowCppConst.html – Robert M. Nov 24 '16 at 07:18
  • 1
    And while we're here, [What is The Rule of Three?](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) Well, it just happens to be one of the, if not the, most important reasons for one of these. – user4581301 Nov 24 '16 at 07:30

1 Answers1

2

This is called copy constructor. When you want to initialize a class instance by copying an existing instance, you'd probably want to use it.

const - you don't want to change the object you are copying.

reference - you don't want to copy the existing instance into the constructor, just to copy it again in the initialization.

Eliran Abdoo
  • 611
  • 6
  • 17