This C++ program illustrates copy-constructor in a class. A copy constructor is a special constructor for a class that is used to make a copy of an existing instance of the class. A copy-constructor looks like a constructor with an object of same class as an argument.
Here is the source code of the C++ program which illustrates copy-constructor in a class. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to illustrate copy-constructor in a class
*/
#include <iostream>
using namespace std;
class Base {
int i;
public:
Base(int ii = 0): i(ii) { }
Base(const Base& b)
{
this->i = b.i;
}
void setData(int ii) { i = ii; }
int getData() { return i; }
};
int main()
{
Base b;
cout << "b::getData = " << b.getData() << endl;
cout << "b::setData = 10" << endl;
b.setData(10);
cout << "b::getData = " << b.getData() << endl;
cout << "Calling copy-constructor on c" << endl;
Base c(b);
cout << "c::getData = " << c.getData() << endl;
}
$ a.out b::getData = 0 b::setData = 10 b::getData = 10 Calling copy-constructor on c c::getData = 10
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Apply for Computer Science Internship
- Check Computer Science Books
- Practice Computer Science MCQs
- Apply for C++ Internship
- Check Programming Books