using namespace std;
class obj
{
public:
obj(int);
obj(const obj &);
int getvalue(void);
private:
int value;
};
obj::obj(int a)
{
value = a;
cout << "this is constructor" << endl;
}
obj::obj(const obj & ab) // <-- this is copy constructor format
{
value = ab.value; // <-- surprise!, in copy constructor you can use other obj's private value. real no surprise, thus other object is the same type. use a function will ruin the const prefix.
cout << "this is copy constructor" << endl;
}
int obj::getvalue(void)
{
return value;
}
int main(void)
{
obj obj1 = obj(1); // <-- this calls constructor
obj obj2(obj1); // <-- this calls copy constructor
return 0;
}
No comments:
Post a Comment