Times when compiler refuses to generate default functions.


Generally C++ compiler generates default functions like Constructor, Copy Constructor, Copy Assignment operator and Destructor if not defined.

But there are some cases when compiler also refuses to generate these functions.

Consider the below example :

name is a reference and age is a const T.

template<typename T>
class PersonObject {
public:
// this ctor no longer takes a const name, because name
// is now a reference-to-non-const string. The char* constructor
// is gone, because we must have a string to refer to.
NamedObject(std::string& name, const T& age);
... // as above, assume no
// operator= is declared
private:
std::string& name; // this is now a reference
const T age ; // this is now const
};

Now consider what should happen here:

string person1("Tom");
string person2("Mike");

PersonObject<int> p1 (person1, 24);
PersonObject<int> p2 (person2, 30);

p1 = p2;   // What should happen to the data members of p1 ??



Before the assignment both p1.name and p2,name refer to string objects. though not the same ones.
How should the assignment affect p1.name ? After the assignment, should p1.name refer to the string referred by p2.name ? If so, it breaks new ground, because C++ does'nt provide a way to make a reference refer to different object.

C++ refuses to compile the code, it eventually does'nt generate the default functions if the data members are REFERENCE or CONST.

If you want to support copy assignment in a class containing a reference data member or a const data member, you must define the copy assignment operator yourself.


Comments

Popular posts from this blog

C++ Guidelines for Multithreaded System

Signalling System #7(SS7) Protocol.

std::shared_ptr