Give reasonably brief, but complete answers to the following. 1. For a class wit
ID: 3917960 • Letter: G
Question
Give reasonably brief, but complete answers to the following.
1. For a class with several std::string data members (like Card in the project), why can C++ copy objects of the class without an explicitly written copy constructor in the class? -------------------------------------------------------------------- 2. C++ allows constructor overloading. Why doesn't it allow destructor overloading? -------------------------------------------------------------------- 3. When enabling a class to work with iostreams by adding overloaded operator<< and operator>> functions, should they be friends of the class or member functions, and why? --------------------------------------------------------------------
Explanation / Answer
1.If a copy constructor is not given in the class , compiler provides a
default copy constructor but it performs a shallow copy.if an object has pointers or any run time allocation of resource like file handle, a network connection..etc, we need to define explicit copy constructors.If we don't do
that we may face problems because we have copied an object and if the copied
object frees any runtime allocated memory then the object in which we copied
this object will face issues.
2. If destructoe overloading is allowed then there will be issue like which
destructor should be called when the destructor is called with no arguments.
Destructor is just a cleanup function for objects then it should be same(no
need of overloading) and also it gets invoked automatically.Having too many
versions in terms of overloading will create lots of confusion and logically
also we don't need more than one version because the functionality is same.
3. In operator overloading, if an operator is overloaded as member, then it must be a member of the object on left side of the operator.
For example,if we have “ob1 + ob2” (let ob1 and ob2 be objects of two different classes). for compilation, we must overload ‘+’ in class of ‘ob1’ or make ‘+’ a global function.
The operators ‘<<' and '>>' are called like 'cout << ob1' and 'cin >> ob1'. So if we want to make them a member method, then they must be made members of ostream and istream classes, which is not a good or viable option most of the time.Therefore, these operators are overloaded as global functions with two parameters, cout and object of user defined class.Friend is required as they
need to access private members of the class.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.