- needed when the class has dynamically allocated members
- always remember the explicit this pointer of c++
- copy constructor is implemented (algorithm)
- allocate memory for dynamically allocated members
- copy the data from const_argument.member to this.member
- assignment operator is implemented (algorithm)
- check for self assignment
- delete memory for this.member
- allocate new memory for this.member
- copy the data from const_argument.member to this.member
- return this
- when copy constructor is called
- doing initialization with objects, like
- class1 object1(“value”);
- class1 object2 = object1; //object to object assignment
- passing a object by value
- returning a object by value
- when assignment operator is called
- assigning a existing object(object with memory for its data members) a new object
CODE SNIPPET
1: #include <iostream>
2: #include <malloc.h>
3: #include <stdio.h>
4: #include <string.h>
5: using namespace std;
6:
7: class A
8: {
9: public:
10: //ctor
11: A()
12: {
13: cout<<"inside ctor"<<endl;
14: name = (char*)malloc(10);
15: name = "test";
16: }
17:
18: //~dtor
19: ~A()
20: {
21: free(name);
22: name = NULL;
23: };
24:
25: //copy ctor
26: A(const A&);
27:
28: //assignment operator
29: A& operator = (const A&);
30:
31: void showName(){std::cout<<name<<endl;};
32:
33: private:
34: char *name;
35: };
36:
37: main()
38: {
39: A obj1;
40: obj1.showName();
41: A obj2(obj1);//copy ctor is called
42: obj2.showName();
43: A obj3 = obj1;//copy ctor is called
44: A obj4;
45: obj4 = obj1;//assignment is called
46: getchar();
47: }
48:
49: //allocate memory for the data members
50: //copy data members
51: A::A(const A& copyof)
52: {
53: cout<<"inside copy ctor"<<endl;
54: name = (char*) malloc(10);
55: strcpy(name,copyof.name);
56: }
57:
58: //check for self assignment
59: //free the existing memory for .this object members
60: //allocate new memory for .this object members
61: //copy the data to .this
62: //retrun this, for operator chaining, cascade assignments
63: A& A::operator =(const A& obj)
64: {
65: cout<<"assignment called"<<endl;
66: if(this != &obj)
67: {
68: free(name);
69: name = (char*)malloc(10);
70: strcpy(name,obj.name);
71: }
72: return *this;
73: }
No comments:
Post a Comment