Open Side Menu Go to the Top
Register
Copying a class in a class in C++ Copying a class in a class in C++

04-18-2014 , 10:10 PM
Hi,

I'm doing an assignment and the first thing you have to do is write a function that returns a copy of that class? I'm a bit confused, it goes like this:

Code:
class example{
      int array[5][5];
      public:
             example copy();   
};
How do I implement it? Probably very easy.
Copying a class in a class in C++ Quote
04-18-2014 , 11:29 PM
implement the copy constructor for the class.
Copying a class in a class in C++ Quote
04-19-2014 , 03:11 AM
Your compiler should do this on it's own, however if you're using c++ 11 you can implement this very easily:
Code:
example(example&) = default;
You can call it by providing the copy constructor with the class you want to copy as such:
Code:
example example1;
example example2(example1);
Copying a class in a class in C++ Quote
04-19-2014 , 12:09 PM
Right, thanks a lot
Copying a class in a class in C++ Quote
04-19-2014 , 11:54 PM
Okay, I don't know what to do.
I need to implement a copy constructor so I can call it in a function later on and use it to manipulate the image.


I still don't know what the constructor will exactly look like to copy the same array. And then how do I call that copy and use it in a different function?
Copying a class in a class in C++ Quote
04-20-2014 , 07:19 PM
Assign each value in the source array to the destination.
Copying a class in a class in C++ Quote
04-22-2014 , 11:11 AM
And let's say I have another function

Code:
void manipulate() {
                "how do I access the original values here"?
                example copy ();

                example_copy[1][2]? Of course not like that..
}
Copying a class in a class in C++ Quote
04-23-2014 , 01:29 AM
Here try this:

Code:
#include<iostream>
using namespace std;

class example
{
public:
	example() = default;
	~example() = default;
	example(example&) = default;
	int array[5][5];
};

void manipulate(example&, int, int, int);

void manipulate(example& example, int row, int column, int value)
{
	example.array[row][column] = value;
}

void main()
{
	example example1;
	example1.array[0][0] = 5;
	example example2(example1);
	cout << example2.array[0][0] << endl;
	manipulate(example2, 0, 0, 6);
	cout << example2.array[0][0] << endl;
	cin.get();
}
You must be using c++11 to use the default keyword if you're not you will have to implement the constructors manually or use the compiler generated ones(which is exactly what default does). I'm guessing you're using visual studio which version are you using?

Anyways it's pretty obvious you have little understanding of c++ syntax and object-oriented design, you definitely should read up more if this is a c++ class you are taking. If you have any questions feel free to ask.
Copying a class in a class in C++ Quote

      
m