Can anyone please explain to me what's copy constructor and how does it work(explain its syntax plz)? i am not sure whether i am understanding it correctly. Does it only run after an assignment operator is used?
A copy constructor initializes the object with the contents of another existing object (hence the name "copy constructor" because the new object will be a copy of the existing one).
The copy constructor's signature is:
MyClass(const MyClass &); // almost the same as yours, but you omitted the `const'
Here's a Whine class example, which should make things easier to follow.
Usually, the compiler will generate a default copy constructor for you, which does a member-wise shallow copy (it copies every member/data field).
This becomes a problem when the object being copied contains pointers, as the copied pointer(s) will point to the same memory address. In such a case, it's necessary for you to write a copy constructor.
Here's a stupid example of this. Let's say we have two people named Steve and Bob respectively. Steve has owns a red house, and bob a blue one. Bob wants to paint his house red, like steve's house.
#include <windows.h>
#include <iostream>
#include <string>
class Person;
class House {
public :
House() {owner = NULL; color[0]=color[1]=color[2]=0;}
__int8 color[3];
void whoOwnsMe();
void paint(__int8 R, __int8 G, __int8 B) {color[0]=R; color[1]=G; color[2]=B;}
Person* owner;
};
class Person {
public :
Person(std::string string) {name=string;}
std::string name;
House house;
};
void House::whoOwnsMe() {
std::cout << "My owner is " << owner->name << "!" << std::endl;
}
int main(int argc, char* argv[]) {
Person steve("Steve");
Person bob("Bob");
steve.house.owner = &steve;
bob.house.owner = &bob;
steve.house.whoOwnsMe();
bob.house.whoOwnsMe();
steve.house.paint(255, 0, 0);//steve has a red house
bob.house.paint(0, 0, 255);//bob has a blue house
bob.house = steve.house;//bob also wants a red house
steve.house.whoOwnsMe();
bob.house.whoOwnsMe();//steve has two houses
std::cin.get();
return 0;
}