I have this A class with a heap member ‘a’:
class A {
protected:
char *name;
public:
// Constructor
A() {
name = new char[10];
strcpy(name, "Undefined");
}
// Assignment Operator
virtual A &operator=(const A &rhs) {
if (this == &rhs) {
return *this;
}
delete [] name;
name = new char[10];
strcpy(name, rhs.name);
return *this;
}
// Destructor
virtual ~A() {
delete [] name;
}
};
I have the subclass B with additional variable ‘b’:
class B : public A {
int b;
// Constructor
B():A(),b(0){}
// Assignment Operator
virtual B& operator=(const B& rhs) {
if (this == &rhs) {
return *this;
}
delete [] name;
name = new char[10];
strcpy(name, rhs.name);
b = rhs.b;
return *this;
}
// Destructor
virtual ~B() {
delete [] name;
}
};
I have the subclass C with additional member ‘char* name’:
class C : public A {
int* c;
// Constructor
C():A() {
c = new int[10];
for(int i = 0 ; i < 10 ; i++) {
c[i] = 0;
}
}
// Assignment Operator
virtual C& operator=(const C& rhs) {
if (this == &rhs) {
return *this;
}
delete [] name;
name = new char[10];
strcpy(name, rhs.name);
delete [] c;
c = new int[10];
for (int i = 0 ; i < 10 ; i++) {
c[i] = rhs.c[i];
}
return *this;
}
// Destructor
virtual ~C() {
delete [] name;
delete [] c;
}
};
I wonder if this is the correct way to implement operator= and destructors for B and C.
Is there any way to call A’s operator= or destructor in B or C, so I don’t write assignment for all members again and again.
- A is base class with a heap variable
- B is a class derived from A, with additional ‘int b’
- C is a class derived from A, with additional ‘char* name’