Question about copy constructors and overloading =

From my understanding the only time you would need a copy constructor and an overloaded assignment operator is if you were to have dynamic variables. However, are such functions necessary when one is dealing with a class that has a member variable that is a string? I think strings are similar to pointers but does that mean that for classes which contain strings as member variables you would need to overload = and also make a copy constructor? Below is an example of what I mean:

1
2
3
4
5
6
7
8
Class person
{
public:
//some functions
private:
string name;
short age;
};


Would such a class need an overloaded = operator if I were to do the following:

1
2
Person a("Bob", 5), b("Frank", 2);
a = b;


would a be just a shallow copy of b?
Strings are actually more related to deque<char> or vector<char> then they aer related to pointers. Any class that is created you would need to create an operator= if you intend to try to set it equal to something. Even strings have an operator= that it runs each time to try to set it equal to something. In fact, strings have at least 2 because it has one for other strings and one for char*.

If you declare s as a string then type s. in your C++ program, you usually get a list of all the functions and variables inside the class, some locked because they are private and other unlocked because they are public. You will see the operator= in the list along with many others that you generally wouldn't think of that is in there .

Since strings are already set up so you can set them equal to other strings, yes it will help you when you create an operator= for your class but you must have it so that the program knows what to do when it sees it.
Topic archived. No new replies allowed.