0

I created a class named view and NetBeans generated a constructor and a destructor. It also generated a method that takes parameters. I'm not sure what the method that takes parameters is or why it was generated. Can someone tell me what this line of code is:

class View {
public:
    View();
    View(const View& orig);          //what is this line?
    virtual ~View();
private:
Ron
  • 14,674
  • 4
  • 34
  • 47
OOPNewbie
  • 11
  • 2
  • 2
    Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and check out the classes section – NathanOliver Apr 12 '18 at 13:08
  • 2
    Copy constructor. And I don't think autogenerating these functions is a good idea - netbeans certainly is not a great C++ IDE. –  Apr 12 '18 at 13:08
  • Thanks. I'll read up on copy constructors and switch to Visual studio. – OOPNewbie Apr 12 '18 at 13:16

1 Answers1

0

It's called a copy constructor

A copy constructor is a member function which initializes an object using another object of the same class. And a copy constructor can access private members too of the passed object.

for example:

class View
{
private:
    int var1, var2;
public:
    View(int var1, int var2) { this->var1 = var1; this->var2 = var2; } 

    // Copy constructor
    View(const View &orig) {this->var1 = orig.var1; y = orig.var2; }  //Note we are accessing private members of orig

    int getvar1()            {  return var1; }
    int getvar2()            {  return var2; }
};

in main:

int main()
{
    View v1(10, 15); // Normal constructor is called here
    View v2 = v1; // Copy constructor is called here

    // Let us access values assigned by constructors
    cout << "v1.var1 = " << v1.getvar1() << ", v1.var2 = " << v1.getvar2();
    cout << "\nv2.var1 = " << v2.getvar1() << ", v2.var2 = " << v2.getvar2();
    return 0;
}

You will see that the members of v1 and v2 have same values assigned.

In most IDEs, copy constructor is "written" in "background" even if you don't write it. That means that you can assign one object to another of the same class type without writing copy constructor in class declaration.

Nick
  • 106
  • 2
  • 10